#internals-and-peps
1 messages · Page 53 of 1
Welcome
i have a quick little syntax question
how do I say is not bigger than in python
!<=
I am running visual studio code
and , opened a file which is present in C:/users/com/Downloads/File.py
when i run the code, try to import something it checks for the file in directory C:/users/com/ and not in current directory
@cloud crypt u figured out a way to get the address of a memory view yet?
I meant I just generally like their concept
I actually thought several times what would happen if I messed with process memory writing, but I am too afraid python would just segfault :p
I used process memory writing for some bots and I had not yet a segfault error o:
I meant writing to python's process
U guys mess with process memory and it’s fine, I do selenium.webdrivers.Chrome() and it segfaults 😒
How to prevent my python program from reverse enginerring and cracking
I have added the authentication method on the start,
PyArmor
A way to protect your python program against reverse engineering and cracking
(I mean sure it’ll help a little)
Imperfect obviously
Python is pretty bad at not being cracked. C, C++, Haskell, ... do much better
Always wanted to try and make an uncrackable c++ thing using intel’s SGX, but idk if it’s possible :/
At least cracking
They could easily break the execution of code when my python program check for authentication
@unkempt rock I am using PhantomJs because headless chrome does not allow clipboard copy/paste
hello guys, so i wonder if there are any tools where i can store both indexes and its values in a data structure? do python have built-ins for that?
basically i dont want to lose my order of values
You can store (item, index) tuples
OrderedDict maybe
lists are ordered
as long as you dont need to access by index :p
ordered but i will mess up with data, so i need to change indexes when i operate along
so when i sort the data, a new index order is needed
ordereddict? i'll check
@flat gazelle how do i do that? any starting tips?
@final whale how is this one structured?
@raven pike you can use dictionary
i want to use dictionary actually, i havent used dictionary in my project
you can use a list with tuples and sort the list by the tuple with the index. ``list.sort(key=lambda tuple: tuple[1])` where 1 is the index of the sort index
i'm dealing with pandas, and have to do row by row cals. so i need more faster operation instead of using pandas built-in operations
they are so slow
Pandas is partly writting in C, you most likely won't write a function in pure python as fast as pandas built-in functions are
i mean using groupby for example is costly, however i can do that in python if i know what i'm doing? that's my thought process
Connecting transistors together until they compute things
How was the assembly language compiler compiled
That's probably more fitting for offtopic
i'm excited that python is considering type hinting more and more. i love it's not strict, and it's rather declarative
the reason why c++ is hard because the creator of cpp doesn't knew good english
and their documentation isn't proper enough
Python already has type hinting for functions which is cool : )
the reason why c++ is hard because the creator of cpp doesn't knew good english
...wut this is the dumbest thing ive read today
I didn't explain myself very well in the python ideas thread I just replied to
But I don't think there's going to be much discussion there.
In a nested loop, does the continue keyword only affect the current loop that the keyword is in?
for instance:
for index1 in list1:
for index2 in list2:
if index1 == index2:
continue
will the continue in list 2 affect list 1?
Yes it won't affect the outside loop, it affects the closest loop
Which is the one looping over list2
Second question I have is what the hell was Nicolas Swift thinking with his A* algorithm?!
Here's the code in question
@copper kayak go to the help channels mate
oh ok
You're in good company then.
@final whale This is not a help channel. Please read the channel description. Check out #❓|how-to-get-help
What type do DAYS and MONTHS have?
whoopsie
days and months are tuples of strings
want me to delete and take it to a help channel ?
deleted and moved to a help channel to avoid cluttering
Is there really no way in python to parse * as a command line argument? I think argparse can do it, can anybody confirm?
@unkempt rock This is not a help channel. Please read the channel description. Check out #❓|how-to-get-help
@grave jolt already did some hours ago
alright, but if u know the answer u can just type here.
what exactly is the base type for a iterable object in python?
because list, tuples, dicts can all be iterated over
but what is their base object type then if you were going to type hint it?
collections.abc.Iterable or typing.Iterable iirc
You'd use typing.Iterable, yeah
They do not have a common base type afaik, you need either (__getitem__ for int and __len__) or (__iter__). Not sure if an abc can specify this
it seems they do fall under typing.Iterable still
according to how isinstance sees it
Being an iterable is just that the interface exists
mhmm
There's no common type but checking with the abc should work
@spice pecan do u know this #help-chestnut?
Please don't ping random people and don't advertise your help channel.
@swift gust This is not really the appropriate channel to get help from, you might want to consult #❓|how-to-get-help
im sorry
Hello, anyone remember what is the setting jSON to set to auto clear console before a run with VS?
(And wrong channel to ask for help)
thank you and sry
This is not a help channel, please see #❓|how-to-get-help
👍
afaik there isn't, but you could always implement one yourself by subclassing collections.abc.Mapping
actually i think i have a workaround. i'll just let the dictionary be allowed to change and then i'll just commit the contents to a db, which was what i was going to do anyways
it's really true when people say 99% of ideas are just dumb lmao
Does the email address distutils-sig@python.org present at the top of the page(https://docs.python.org/3/installing/index.html#installing-index) can help somebody with an issue with the topic?
Can someone please explain atomic operations in python ?
Python has a lock (GIL) that means only 1 thread can run at once - any operation during which the GIL cannot be released is atomic in python
So a lot of operations on builtin types are atomic
(This is not the same as atomicity on a processor level, or in lower level languages, but those don’t really matter here)
I think this translates to any single python bytecode instruction is atomic? (Or something like that)
Mentioning this here based on @unkempt rock's recommendation but I am looking for someone who has used pyinstaller to help me sort out some dependencies
what's really the point of an elif if you could just keep making if statements?
You can include a default case after if, elif, elif, elif, else
ahh ok
else will run when no other (el)if statement is executed
yeah, thanks for explaining :D
what's really the point of an elif if you could just keep making if statements?
because a chain of ifs is not semantically equivalent to a an if elif
I am also interested in this question. Is there any difference in how code is executed if you use a bunch of ifs as opposed to a bunch of elifs?
All the ifs are executed, but an elif only gets executed when the conditions above it didn't pass
an equivalent to elif is
if cond:
...
else:
if elif_cond:
...
``` but you can see why the elif was included when indentation is syntax
Awesome! Thanks for the explanation.
hi
i need some little help
i want to imprt file in my script , but the file is not in the same diractory
how i can do it
this isn't a help channel. see #❓|how-to-get-help
I'm confused. How can a = b or c work?
a will be a bool
It takes which ever value is True or False if both are false
that was a bad method of explaining that
Not necessarily, pyhon will evaluate the truthy values of the expressions and return the first result that's True or the last one
You are not allowed to use that command here. Please use the #bot-commands channel instead.
its the same principle of doing:
if b or c:
# one of those values is true```
Oh, sorry. I sent the same over there
Yeah, I get what it does, I'm confused as to why however
Oh interesting so it will take the first value if both are true? @astral forge
Anything that is not False or 0 can be cast to a True, correct? Why doesn't that return a bool?
Everything can define its own bool value. For the why, why not? They are not boolean operators
@radiant fulcrum I was expecting a bool, so that is completly unexpected for me xD
But ye, seems like it does
At least not in the same way as & or | are in other languages that is
This is called 'short-circuit evaluation'. It can be useful to pick the first non-falsey value:
config.get("user") or config.get("username") or config.get("user_name") or "<default>"
The cool part is that it will not evaluate expressions it doesn't need to. Here, for example, if config.get("user") succeeds, it won't compute the other expressions.
Well, it makes sense as I used the same feature in js before
You can read about the expressions here https://docs.python.org/3/reference/expressions.html#boolean-operations
I just thought it would be a bool in python... 😂
In one help session I gave this example. Maybe it's a bit too contrived, but it demonstrates the point, kind of.
!e
class First:
def __init__(self, fn):
self.fn = fn
self.computed = False
self._value = None
@property
def value(self):
if not self.computed:
self._value = self.fn()
self.computed = True
return self._value
def __bool__(self):
try: self.value
except: return False
else: return True
def __repr__(self):
return f"First(lambda: {self.value!r})"
print(First(lambda: 1/0) or First(lambda: a) or First(lambda: "hello"))
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
First(lambda: 'hello')
You can eval code in here?
Here I take advantage of lazy evaluation. .value is a 'lazy' property -- it doesn't get evaluated until it's demanded.
ô.o
Helpers can do that
Others can do that in help sessions, if I'm not mistaken.
And in #esoteric-python
Gotcha! I think. Thanks!
Please don't advertise your help channel.
also, works when i compile in console mode, and it looks like pyinstaller compile and includes all file in onefile but can't file them during execution
I may of missed something in PEP622, but what happens if a function returns a Boolean, or an integer? Since true can be evaluated to 1 and false 0.
match f():
case 0:
print('x')
case False:
print('y')
case 1:
print('a')
case True:
print('b')
Ex, if f returned False, would the first and second case run, would they both run, or would it break after the first case succeeds?
is there any push to make anything that accepts a string accept a pathlib object? sometimes something will accept both, sometimes it'll work with pathlib.Path object but i'll get a linting error, and sometimes I'll have to convert to a string
Most of the standard library should with both
it does ( though i just had a linting error using shutil with one ), but some other modules don't. Maybe I should look at the source for something, I don't know how they're typically handled, if a pathlib obj is passed is it converted to a string, or if a string is passed is it usually converted to a pathlib obj?
Probably the former for most things considering they already used those
so converting to string and then using os.makedir would be prefered over Path.mkdir ?
Wait you're going to be able to use match as a switch statement?
The way I understood it, it was for determining comoposition of objects
@swift imp i never worked out what you were doing with .pdbrc
What didnt u work out?
do you have a link anywhere to what you were talking about?
you were talking about it as though there was some sort of different approach, using pdbrc, to putting breakpoints in code
I'm pretty sure match is possibly Python's future implementation of a switch statement from C++, or a match statement from Rust.
@magic python are u on linux or windows?
mac os
all pdbrc does for me is provide an alias for interactive ipython session from within ipdb
you have a file called .pdbrc that goes into your HOME directory
yeah i have that
ok
so
add a line like
b <path to a file you want to do a breakpoint>/file_you_want_add_breakpoint_.py:<line you want to add breakpoint>
in ~/.pdbrc ? and this is easier than putting breakpoint() where I want a breakpoint? It looks like more work, but maybe i'm missing something
when u fire up ipdb you'll see that the breakpoint is added
its less work because you don't have to change the file you are debugging and then manually remove it later
So, don't use the .pdbrc file, you have to manually add that breakpoint() and then remove that breakpoint() when youare done
where as you put that line your .pdbrc and it only becomes active if you start ipdb
interesting, yeah maybe that could be handy 🤔
where can i find documentation on this?
https://docs.python.org/3/library/pdb.html?highlight=pdbrc is where i'm looking atm
just look up docuimentation for pdb
anything you would do in pdb, you can do the pdbrc
it's not documented in there afaict though
i mean - what you've written would be a pretty good guess given the documentation i've linked
!pep <pep_number>
Can also use: get_pep, p
Fetches information about a PEP and sends it to the channel.
oops wrong
!pep 478
Python has a lock (GIL) that means only 1 thread can run at once - any operation during which the GIL cannot be released is atomic in python
@unkempt rock thnx
python is the best programming language
python is the best programming language
Hey can anyone help me to build a python script to automate filling email address in html form using selenium and regex
*any html form ( regex use is compulsory)
Hello, @unkempt rock, this is not a help channel, but a discussion channel to discuss the Python programming language itself. For shorter, more general questions, #python-discussion could work, but we also have up to 32 help channel available (dynamically scaled), see #❓|how-to-get-help.
We're slowly moving into the final phase of the Python 3.9 release. Exciting.
I think I'll do a compile today
The new parser is pretty cool, as in it can do more/different things
That python-ideas post from Guido received some criticism (the pseudo print statement one), but it's an interesting "proof of concept" to show what's now easily possible
And that's how I mainly read the message
Being able to assert back and forth is quite handy yeah, I hope we'll some more funky grammar in the future
What does this parser able to do compared to the old one? What's the highlight?
There's a comparison of LL(1) parsers and PEG parsers in the relevant PEP: https://www.python.org/dev/peps/pep-0617/
I'm not qualified to try and give you a thorough explanation myself
The whole thing is that an LL(1) parser will run all the possibilities sequencially, while the PEG will explore each layer horizontally before moving down. It means that PEG aren't context-free grammar and allow more things to be specified in the grammar rules including lookhead and lookbehind assertions. Python initially used the LL(1) parser outlined in the dragon book (from where I take all of those informations) which is a quite old book from the 80s, when every byte of memory mattered and so lookahead and lookbehind were just a no, because it used too much memory.
@mint forge nice
The subreddit on Pep 622 is gnawly.
!pep 622
I'm starting a new project. How ready is 3.9?
If you want to start an actual production project now, I'd not recommend starting with a beta version. There will still be support for Python 3.8 for over 4 years.
Pep 622 would be for 3.10?
Well, it's not a production thing but hey
If it's usable and kinda stable I'm all in
Useable is relative, since except some edge cases, libraries with binaries either won't support it or you'll have to compile them yourself hoping everything works
Oki doke. Thanks
@glass robin
Python-Version
3.10
can the i in "for i in range()" be replaced with any other letter? and can %s in prints be replaced too?
where?
if you are not using the variable while looping, consider writing for _ in range(...)
and yes you can totally use any valid identifier you wish
I don’t know why would you use %s for string formatting because f-strings are a better solution
Anyone ever gave a shot at writing their own version of the CPython interpreter?
what do you mean under writing own version of CPython interpreter
i'll rephrase, your own interpreter for python
my thesis task is basicly to write a pyton interpreter using bytecode as it's direct input
it’s a very large task to do
i am aware
then again it's basicly write the ceval part plus objects
i realise i won't be able to implement probably 90% of the functionality that cpython has to offer, and probably won't cover the 99% of the language spec
still, will probably offer great insight into the internals of python
im just wondering if anyone here attempted something like it
@brazen jacinth I've forked cpython and messed around with it. PyPy and Jython are other implementations.
I think I read that cpython is smaller than the compiler for Java, but Java code makes more guarantees than Python code about what a given line does.
is that due to the fact that it's dynamic vs static, or are the differences bigger then merely that?
not the right channel @raven depot, see #databases, or #❓|how-to-get-help if you have a specific question
@brazen jacinth I assume it has something to do with that. When you use the dot operator to access an attribute, it's not actually guaranteed that that object has that attribute, but it's not guaranteed that it doesn't have it either.
Even between instances of the same class, you could arbitrarily give one instance an attribute that another instance doesn't have.
!e
class A: pass
a = A()
a.thing = 'hi'
print(a.thing)
b = A()
print(b.thing)
@boreal umbra :x: Your eval job has completed with return code 1.
001 | hi
002 | Traceback (most recent call last):
003 | File "<string>", line 6, in <module>
004 | AttributeError: 'A' object has no attribute 'thing'
Even when you know the type of an object, you're not even guaranteed to know what attributes it will have. But this is just a small part of the picture.
Looks like you can arbitrarily delete instance variables with del as well.
yea, interpreter and runtime overhead + constant type checking plus what you mentioned
kinda makes sense given the fact that this is a code snippet representing the implementation of a basic arithmetic operation with 2 objects
definitely appreciate static types in some sense more given this info
i wonder if given mypy anotations basically everywhere, as in right in the implementation directly, would it help speed up common operations significantly
ooh yay c 🙂
can i ping you later in #c-extensions when i need help with implementing stuff like __index__ and whatnot for my classes?
When datetime stores a datetime associated with a specific timezone, does it store it as utc internally and do conversions as needed?
I'm listening to the latest episode of talk python
If I have a datetime for 1pm in New York and 1pm in Chicago, I want subtracting Chicago from New York to give me a time delta of one hour, not zero.
Not sure which it does.
wait can i append to a list by doing list += "a" or whatever
that's synonymous with .extend
and .append right?
@visual trout there's no operator for appending to a list.
You're right @solemn jewel
.append is a single object, .extend is all objects from an iterable
You can even append a list object to list, but then the list itself is an element
Whereas extend joins the lists
so if i have say this list list_ = [1, 2, 3]
i can't do list_ += 4?
and then list_ is now 1, 2, 3, 4
Nope
you cannot indeed
no, but you can do list_ += [4]
No, you can't do that; the inplace add is for extending a list with iterables, yeah
I've been meaning to implement my own list class where << is append
Which idea came from another helper.
You can also do list_ += 4,, which will create a tuple with 4 as its only element (due to the trailing ,), but surrounding the item with [] is way more readable imo
@boreal umbra Should be trivial if you subclass UserList
Yeah
The same helper said something about implementing the bitshift operators for deque
for i in prefixes: prefixes += [i.upper()]```
I'd ping the ones who I think it was but I don't want to disturb them.
Yeah, salt gets crazy
so i can do this right?
Stelercus from the code, sub does base + otoff - myoff where base is a timedelta where everything's subtracted and the offs are offsets
so that my list has one version in lower case and one in upper?
it'd be better to just use prefixes.append(i.upper())
File "Backtick.py", line 10, in <module>
for i in prefixes: prefixes += [i.upper()]
MemoryError```
turns out it didn't work
but yeah, thanks!
@peak spoke I didn't understand that too well but I'll look at the code next time I'm at my computer
@visual trout that's a memory error
What is prefixes?
File "Backtick.py", line 10, in <module>
for i in prefixes: prefixes.append(i.upper())
MemoryError```
No, you have infinite iteration
a list with strings
Is it some huge thing?
3 strings to be precise lol
for each item in prefixes you add an another prefix
prefixes = ["c#", "js", "py"]
oh right
i know how to fix that tho
one sec
damn feedback loops
iterate over a copy
That won't work, I don't think
Basically a delta is created from the two datetimes you're subtracting and if they're both aware then it's also time_delta + other_offset + my_offset https://github.com/python/cpython/blob/master/Lib/datetime.py#L2088-L2110
for i in prefixes[:] or for i in prefixes.copy()
And you have to use range(len(prefixes)) instead of just len(prefixes), if you're going the indexing route
You could just do [e.upper() for e in prefixes]
So assuming new york and chicago aren't the same timezone then the output != 0
thanks guys
yeah, something like prefixes.extend([e.upper() for e in prefixes]) should be more elegant
Iterating over a range of numbers and then subscripting the container you really care about usually isn't the way to go.
so you're saying i'm doing it wrong?
I would honestly just check with .lower() rather than adding both copies
Sorry @visual trout, do you feel that I've offended you?
no no
i was just joking
i really appreciate the help, i truly do
prefixes.extend([e.upper() for e in prefixes])
soooo
this piece of code then (not mine)
Would you like to dissect why that code works?
can i do my best to try and explain it first?
Yes, that would be great.
[e.upper() for e in prefixes]
this part creates a separate list of my list but in uppercase
and the .extend just adds it to my original list?
Yes, that's exactly right
and this is better because i'm not editing my list as i'm looping through it
right?
Right
The list comprehension, which is the little for loop like part, gets evaluated first.
And it's making a separate list based on the first one
The first one isn't changed during that process.
sounds clever
e.upper() for e in prefixes
this piece of code
what is that "thing" called
like
A list comprehension
List comprehension?
oh
i'm gonna have to read up on that
see
i only started actually investing time into python and stuff a month or two ago, and stuff like this really helps
people that actually stop to explain
They're one of the most elegant features of python, in my opinion
thanks for you time!
they come from haskell afaik
Well, isn't the closest to comprehensions in Js a combination of filters and maps?
@visual trout don't hesitate to use a help channel if you ever need it. Take a look at #❓|how-to-get-help
h_letters.append(letter)
h_letters = [ letter for letter in 'human' ]```
If I'm not mistaken the comprehensions are somewhat unique to Python when it comes to the modern and well known languages.
yeah i thought it was gonna be a small talk thing
but it ended up being a thread of comments
thats my bad
@visual trout you could do that even more quickly with list()
this is an example i found online actually
julia, haxe, C# (if you consider LINQ), Haskell all have comprehensions
two different ways to do it
and probably other langs I forgot about.
julia, haxe, C# (if you consider LINQ), Haskell all have comprehensions
@flat gazelle LINQ too is kind of just a clunky way of combining maps and filters into one function.
can i do list(letter for letter in 'human') instead of [letter for letter in 'human']
!e
bob = 'bob'
print(list(bob))
@boreal umbra :white_check_mark: Your eval job has completed with return code 0.
['b', 'o', 'b']
Just list('human').
oh right
Seems less readable to me.
list is the class that lists belong to, but when you call it like a function, it converts that thing to a list, as long as it's an iterable.
ye, unpacking into literals is rarely used
letter for letter in 'human' why is the index variable name thing being typed twice
usually you want to be modifying something in a comprehension, but you can also use comprehensions for filtering passing_grades = [grade for grade in range(101) if grade >= 60]
yes
The part before that is what you do to it.
like for i or so?
ooooh
Imagine you're iterating just like you usually would, so for letter in "humans" is how to iterate, and then in the front part you're selecting that value and you could even do something like upper(letter) if you wanted to.
Yeah it could
Exactly!
It also works for sets
thanks guys, i'm gonna go to bed now :>
dunno what sets are, not even gonna ask today lol
And any collection that can accumulate from an iterable
And dictionaries. But that's a bit different
wait it's another datatype!?
Mind explaining what tuples are while we're at it?
Sets are a data type
And how they differ from lists. 😅
@shy belfry tuples? Sure.
Do you understand mutability?
it's different every time...?
uh, short answer, no
oh you mean in the sense of not being able to change?
like a tuple
I was asking Dan6erbond
nvm
You can sleep 👌
a tuple is immutable right?
If you want
before i go
Yes
It's also hashable
you might see me around some other day
Do you understand mutability?
@boreal umbra yeah pretty well from the C#/Java context.
@shy belfry tuples are immutable
Once you make a tuple you can't add, remove, or change elements
The best you can do is make a new tuple with the change you needed to make
That makes sense! Is it also more efficient to use tuples in that case?
Don't worry too much about efficiency at that level.
If using tuples makes your code harder to read than using lists, it's probably not worth it.
Yeah I figured that to be the case as well. I was mainly asking because at some point in my code I was copying a tuple's values into a list with comprehension, it never changes, because I needed to get a specific attribute.
Well, if you have a tuple, you can convert it to a list with list()
No list comp needed.
But this has an O(n) runtime
I think
Oh I still needed to do the comprehensions because I was doing [self.getval(item) for item in args]. Haha.
Aha
I wrote a tiny reactive framework to manage callbacks when values are changed, since Python has all these descriptors.
Those were another incredibly weird concept from what I'm used to with C#. Even the custom getters and setters don't compare. 😅
Do people have getters and setters with method syntax in C#?
Because I really hate those.
they have something similar to @property
Yay
Yeah C# lets you define custom getters and setters just below the variable declaration. Unlike Java and that crap. Kotlin does that, too.
Hey guys
Do @cache holds recent x values or first x values?
i mean lrucache i guess?
@raven pike lru stands for Least Recently Used, which are the things discarded.
so it keeps the values that have been used recently (not the ones added recently)
Hello guys, could any one you recommend me any "List of programs to do while learning python" kind of thing, since i heard its better to learn while doing projects, and not by learning by the book
@mystic rain #python-discussion
yes
@magic python while one could ask that in python-general, there's actually a !resources command
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
so you can pull that one out any time
is https://www.python.org/dev/peps/pep-0484/ similar to mypy at all? I'm not familiar with typechecking and stuff, or hinting, but am curious at the mo
That PEP provides the typing module while mypy utilizes it for checking the types
and PEP 484 defines the format of the type annotations that mypy requires to work.
does mypy build off of this then? Is this a relationship similar to attrs and dataclass, where a lot of attrs features were pulled in for dataclass? or not 🤔
Not necessarily, all that mypy does is provide static type-checking but not actual classes for typing iirc
is it considered best practice to use typing? I'm a bit confused, i've used arguments such as
def f(x,y,z=False)
before, where z doesn't have to be passed... but i'm looking at pandas source and see xlabel: Optional[Label] = None, which seems a bit clearer that this is optional...
But - there's also ax = None, and this is also optional... why not have ax: Optional[matplotlib.axes] = None here?
I don't understand properly why there are some optional arguments which have Optional[...], and some that don't
PEP 484 defines the protocol for representing type annotations, and mypy uses it.
I don't understand properly why there are some optional arguments which have
Optional[...], and some that don't
@magic python because type hints are only a few years old, lots of code predates them, and adding them to existing code is a non-trivial amount of work
oh ok, i didn't consider that. Why isn't it simply a case of adding the Optional as there are in others? I assume there's more going on, i just don't get why that'd be much more than a search and replace at the mo
Optional takes an argument in the [] - you need to read the code or the docs to figure out what argument that should be
ah, yeah... Is this the sort of thing that languages like Java or whatever are able to do more easily?
because of explicit types and stuff? Or is this just generally tricky
(i'm referring to the refactoring)
In Java you must always provide the type - so, it's not easier, but it's required that you figure it out when the code is first written.
Needing to go back and add it after the fact is a problem unique to Python.
interesting... i've only recently been bumping into these kinda things tbh, what i'd consider more software enginnering things rather than writing a script, getting the data, and running away.
static langs make the world go round
they seemed clunky, but now i get why people would like them... i guess in a couple of years things will be much more robust (in python) with typing and stuff used overall? 🤔
they are SAFE
and its hard to appreciate that if you havent worked on large scale projects
im a c# dev
ooh come help in #c-extensions cuz my rust is awful
god yes i love rust
yeah, i can get some of that - i only recently found out about * in functions and i really like that it actually enforces something 😄
which is obviously a static lang
is C# any fun? always wanted to try it, but i'm not a huge fan of java
when i write python i miss c# intellisense SO much
im a huge fan of c#
its a great lang
but would i like it even though java is meh?
i hate java
as do i
Java makes me question my will to live.
i'm mainly in pandas tbh, so I'm not sure c# or rust could really replace, the only other is R... but python is better for production already... so I guess I'm stuck with python
glad we're in agreement 😂
c# is java, if you took out all the dumb shit like checked exceptions and added a fuck ton of cool stuff on top
we're all java haters, woohoo
can i drop the c# invite? or will the bot shout at me
it's whitelisted
My pretentious friend liked Java, but then he realized that rEaL pRoGrAmErS write everything in C
so now he likes C
I've heard nice things about rust... but the ecosystem for R and python is so good for data stuff.
maybe i'll just learn typing and mypy 😅
the worst part of rust are the people who code in rust
lol
I really hate the name of mypy
C is awesome if you use it in contexts where you don't need to worry about error handling or cleanup 🙂 (like python extensions since the runtime handles it)
ourpy 🛠️
Python feels so free, but that comes at a cost of course
lmao
tbh i miss static types alot when writing my discord.py bot
im so used to coding with intellisense
do you not find type hints make up for it mostly?
doesn't pycharm do that?
it can help
pycharm seems to do a pretty good job for me
seems somewhat comparable to what clion can provide
and clion's awesome
vs code does pretty well too
pythons dynamic nature means it just cant, cuz it doesnt know things will be
clion is great
its ok
vscode completion is pretty poor imo
does PyCharm have its own linter?
but its not like C# and VS
or does it use mypy?
not even clse
that's true
i find vsc is really slow, and it doesn't fuzzy match substrings etc
i often have to hit ctrl + space to give it a prod
c# even has an ai feature that will train itself on your codebase and suggest ur most likely match
there's a thing for that you can use in python or something, i forgot ( kite? )
its pretty useful, tho some people dont like it
hmm ok team completions looks cool
i'd like something better than vsc, i had a look at pylance and that didn't seem to do much either
i'll be honest, i never felt that intellisense outperformed whatever clion has (some clangd thing?)
i jsut installed pylance
didn't seem to make any diff for me
you have to turn it on
tho some new features are cool
unused imports are nice
and auto import
i think , i can't remember what it is.... whether there's some pre-commit thing for it
swear pycharm already does all this tho
what's this
like seriously try it out
vsc is working fine for me rn, tho i use rider for c# sometimes
i have pycharm pro but i've used it like once lol
flake8 already highlights unused imports though
yeah, i like vsc better
flake8 already highlights unused imports though
it doesnt grey out unused code
ah, i'm used to jetbrains
no it gives it wiggles and if you have errorlens installed you'll get a big bar
IDEA is a great platform

yeah i use vim keys in vsc... they're OK... i feel it might slow it down a lot though

like slowed down the editor?
it doesn't? I was wondering if that's why my completion is crap
well idk then, maybe vsc is a bit crap i guess
vim keys aren't vim imo
vim binds are lmao
🤷♂️
vim binds are the key draw of vim
I wouldn't say i'm a vim person, but i use vim keys everyday
This is all way off topic for this channel
This should either go to #tools-and-devops or an off topic channel
super() is shorthand for super(ClassDefiningThisMethod, self)
and it's beautiful, especially when you inherit from multiple classes 🙂
And what it returns is a proxy object such that any method or attribute accessed on it will come from the a class that's after ClassDefiningThisMethod in self.__mro__
how does it work as a shorthand? Does the parser just handle it in a special way?
I think so
interesting
so does it implement __getattr__ in a special way that intelligently searches the mro?
https://www.python.org/dev/peps/pep-3135/#specification - yes, the no arg form is special cased by the parser.
And yes, the proxy object that is returned when you call super has a getattr that looks at the mro of the object it was bound to, and skips over classes before the specified one.
and it leverages the descriptor protocol to pull that off, I believe.
I'm reading through the PEP, but I wonder, if super() was going to get special treatment by the parser anyway, why require the parens?
it was already a function, and there's still valid use cases for calling the two arg form (mostly backwards compatibility, but it could potentially be useful even without that)
I like the look of super.__init__() better.
so, making it both a function and an always-available implicit variable seems like it'd be unduly confusing.
that'd be a lot more magical, too. when you see super().__init__(), it's clear that super is a built-in function that returns something to you - that's not at all clear in super.__init__()
I've always thought super().__init__() was confusing, so that apparently wasn't solved 😛
seems like it was proposed - https://www.python.org/dev/peps/pep-3135/#super-foo-self-args
I think the two arg form was a lot clearer and less magical, but also far more verbose, so... 🤷
people often got the two-arg form wrong.
the order of the two arguments?
they put the parent class instead of their own class
I remember someone was doing an exercise where they had to make a Mom and Dad class and inherit from both
because they think they have to invoke the method on the parent
it's understandable
ah. yeah - but that's a total misunderstanding of what super does.
I ended up advising them to do Mom.__init__(self, ...) and Dad.__init__(self, ...)
@boreal umbra ick
also both __init__s had different signatures.
an understandable misunderstanding, because super has a terrible name, but...
people who are familiar with the concept of super from another language will have absolutely no idea what super does in Python, and that seems... less than ideal. Because it doesn't call something on the superclass, not necessarily. It calls something on another class, which may be a sibling class instead of a parent class.
@spark magnet I'm not sure how else they could have finished the assignment because the Mom and Dad class were neither subclasses of the other, and their __init__s weren't the same, though I don't like the way the assignment was designed.
@boreal umbra yeah, that seeems like a bad exercise
Python's multiple inheritance is cooperative. Every class participating in multiple inheritance needs to have been designed to support it, in order for it to work properly.
even if a class thinks it has no base classes, it needs to call super(), for instance.
why
yeah what?
because super delegates to the next class in the MRO, not just to the superclass, and the next class in the MRO might be a sibling class, rather than a parent class.
maybe I misunderstood. I thought you were talking about classes that inherit only from object
I am.
how do the classes that can't be inherited from work?
@boreal umbra it's a common misunderstanding to think that because you know what you derived from, that you know where super() will go.
you've got two classes A and B that inherit only from object. Now you make a class C that inherits from both A and B. C calls super().__init(...) to initialize A. If A doesn't call super().__init__(), then B never gets initialized.
how would the call to super() made in A.__init__ know to go to B.__init__?
@boreal umbra because it has self, and it can see that the MRO has A and then B
I see
So the sequence of classes to visit for __init__ing is more like a linked list than a queue?
this is a very tenuous comparison
let me think of a better way of explaining it.
So the call super().__init__(self, ...) only guarantees that one more call to a method named __init__ will occur, yes?
In [82]: class A:
...: pass
...:
In [83]: class B:
...: pass
...:
In [84]: class C(A, B):
...: pass
...:
In [85]: C.__mro__
Out[85]: (__main__.C, __main__.A, __main__.B, object)
I'm familiar with MROs
super() takes 2 arguments - a class, and an instance. It skips over all the classes in the instance's MRO before the specified class, and then looks up the given attribute on the next one after the specified class.
So unless you're sure that a given class inheriting only from object won't be used in a multiple-subclassing situation, you have to include super().__init__(self, ...) to ensure that it keeps searching the MRO for sibling classes that ended up further back in the MRO?
it won't automatically "queue" those calls for sibling classes?
yes, if a class wants to behave properly in a multiple-inheritance scenario, it must call super(). Multiply inheriting from one that doesn't can do the wrong thing.
fascinating. Thanks for explaining that
https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ explains this better than I could, @boreal umbra 🙂
No one can explain it better than you 
So, I have a string ("7.50") and i am converting it to a float (float("7.50")) but it makes it look like 7.5 rather than 7.50
How do I make it show the trailing 0?
floats cannot store that trailing zero, so you have to keep it in string form or convert it t string with 2 decimal spaces
I think this is what you want: '{:.2f}'.format(3.141592653589793)
!e
print('{:.2f}'.format(3.141592653589793))
You are not allowed to use that command here. Please use the #bot-commands channel instead.
probably better to do format(3.1415, '.2f')
Thank you guys 😄
probably better to do
format(3.1415, '.2f')
@flat gazelle hmm, true, that's a bit more readable!
I forgot about the format builtin.
Is there a way to return a value, and add extra functionality to it? At the moment I'm creating a class that inherits from the previous type, and adding those methods I need, but this doesn't work for bool and NoneType unfortunately.
Well, you could look into decorators
That would allow you to customize the return value of a function
I think I might be explaining this wrong... What I'm trying to do is let's say I have the boolean value True that I want to return. But I also want the user to do this:
val = get_value()
# >>> True
val.method
# >>> custom method
oh, you want the user to take additionnal steps after getting their returned object ?
Precisely, more specifically what I'm trying to do is work with advanced descriptor functionality:
def __get__(self, instance: Any, owner: Any):
class ObservableProperty(type(self.value)):
name = self.name
history = self.history
on_change = self.on_change
return ObservableProperty(self.value)
defining a class inside a method… pretty harcore ! 😄
Well, ok, and what should the user do after getting their ObservableProperty ?
Haha! Yeah, it sure is. I've been trying to muck around with all these crazy features Python offers to create ReactiveOwners... I already published a version of the library that works, but it's only functional with types that aren't None or bool.
Well, ok, and what should the user do after getting their ObservableProperty ?
@sterile kernel here's an example from my tests:
self.test_class.name.on_change(call_change_name)
self.test_class.name = "Bar"```
You can access, set and of course use the extended functionality from that variable.
I don't get the problem… Doesn't it work as-is already ?
Furthermore, nothing (get/set value) is mandatory, is it ? So you really don't need to do anything…
This unfortunately doesn't work for bool and None, no. :/
For everything else it does seem to, though!
But bool and None are "final" in Python.
At the moment I just raise errors when a user uses those.
But it's not that great because bool in particular should be reactive.
Maybe, it's because bool and None are singletons, yeah
There's only ever a single instance of None, and there's no point in setting it to another value.
Exactly... So there's no way to cleanly do what I want?
I'll probably have to add some if/else statements along the lines then.
I don't see any way, no…
Alright, thanks for the help anyway! 🙂
no problem ;p
Tbf python isn't built to do this sort of things
Python is the only language I've managed to do this kind of crazy stuff with descriptors in the first place, though. :P
Those inline-classes inheriting from dynamic types... Feels horrible coming from other languages.
But it's enabled neat functionality.
The issue is that you want to have a sort of enriched object, but you would still have some quirk, because it can't technically be the same object
For instance, the ID would be different, which is an issue for everything that relies on hashing, like dicts
True... I haven't even thought too hard about those things because my use-case for this library doesn't really requires those features to work...
how much space is required for the download of -python
The source code is around 30Mb, it should be less for the compiled version
42Kb for the main executable according to snekbox
i think pep563 "Postponed Evaluation of Annotations" just saved me
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from connection import ApiConnection
``` is this the accepted way of avoiding circular dependencies when typehinting, then?
Yep.
That's pretty much the reason it's been introduced.
I use it consistently with aPRAW.
i spent way too long looking for a solution for that in the internet
Hahaha. Took me a while to understand what's going on, too.
Is there a way to create an empty class? If you create an instance of object (the most basic class), it will already have __init__, __init_subclass__, __del__, __delattr__ and more, but I don't want nothing, nor methods nor attributes
you would need to recreate type and object from scratch then or something
:|
or bypass their stuff
damn i never though this was going to be soo hard lol
Why would you need that?
idk
yesterday i lost access to internet and i was bored, so i was playing with python
then i did some js
and then it came to my mind when i was practicing js classes: "is there a way to create an empty class using python?"
pretty sure you always need at least a __class__
thanks
congrats 
im still stuck with developer 
well
so
no way to create an empty class unless you do some fuckery on the python core, right?
I think a python2 old style class is a bit more barebones
What about type("ClassName", (), {})?
uh what?
!d type
class type(object)``````py
class type(name, bases, dict)```
With one argument, return the type of an *object*. The return value is a type object and generally the same object as returned by [`object.__class__`](stdtypes.html#instance.__class__ "instance.__class__").
The [`isinstance()`](#isinstance "isinstance") built-in function is recommended for testing the type of an object, because it takes subclasses into account.... [read more](https://docs.python.org/3/library/functions.html#type)
See the second part
that is not an empty class
It's the same as doing class ClassName: pass
i always thought type is a function
Maybe I misread the question, but it does create an empty class inheriting from object at runtime
@true hollow i don't think you can do what you want.
what is the easiest way to turn any number into an x digit number?
int()
no
like
turn 1 into 001
or 32 to 032
because i know how i could do it
but it would be very not efficient is my guess
my_int = str(my_int)
res = "000"[:-len(my_int)] + my_int
ig this would work
f-strings would probably be easiest, e.g. print(f'{3:03}')
lmao forgot they existed
what does the f do?
just another method of string formatting
Although this probably isn't the right channel for that sort of question
my bad
like:
"{}".format(x)
f strings are like
f"{x}"
but what does the f prefix do?
formats
ah
gotcha
so if i for example tell python to write my single digit but i want it to be 3 digits, it just adds 2 zeros?
no iirc
ah nice
@sturdy timber mind explaining or no?
You should probably open up a help channel, see #❓|how-to-get-help
alright
turns out str.zfill(int) is by far the easiest and most readable way to do it
@visual trout while zfill for this purpose is good, I just wanted to link this page on formatting strings: http://zetcode.com/python/fstring/
Python f-string tutorial shows how to format
strings in Python with f-string. Python f-strings provide a faster, more
readable, concise, and less error prone way of formatting strings in Python.
You can do a lot more with f-strings / format() regarding floats, decimal points, datetimes, padding etc.
Another page on using the format() function: https://pyformat.info/
Yesterday we were talking about how super() is a special case for the parser. On a related note, having class methods for special constructions seems like a popular solution for the fact that Python doesn't let you overload __init__
And typically those class methods do some extra work and then pass some variables to cls()
But what if there's no straightforward way to take the inputs for that class method and create an instance in terms of __init__s signature
anyone leveraging PEP 617 yet?
You could create the instance manually with super().__new__(cls) and set the variables manually but I imagine circumventing __init__ has unforseen consequences.
keeping up with Python updates is overwhelming
anyone leveraging PEP 617 yet?
@near coral https://bugs.python.org/issue12782
Does that mean I can throw away \ from valid uses in normal cases?
so the bug is still out there?
@near coral nop, it is allowed in 3.9 but only in the new parser and it will be part of the language spec on 3.10.
Does that mean I can throw away \ from valid uses in normal cases?
@peak spoke yea, there are no need for it from now on (3.10+)
I mean for this case
Yesterday we were talking about how
super()is a special case for the parser. On a related note, having class methods for special constructions seems like a popular solution for the fact that Python doesn't let you overload__init__
@boreal umbra I'm not sure I exactly get what you mean here... but you can do this in Python to "overload"__init__:```python
def init(self, reddit: 'Reddit', data: Dict, submission: 'Submission' = None,
author: Redditor = None, subreddit: Subreddit = None, replies: List['Comment'] = None):
aPRAWBase.init(self, reddit, data, reddit.comment_kind)
AuthorMixin.init(self, author)
SubredditMixin.init(self, subreddit)
@shy belfry I don't really like having that many if statements
Well, that's not what you're referring to
Where's an if-statement?
Yes, this is inheritance. That's the thing - I'm not sure I get what you're saying about the overloading of __init__? Do you mean really like just overloading functions in general?
Having multiple ways to create instances.
For example
I worked on a library where a certain class was meant to read data from a text file. It would store that data as a list of tuples.
So the __init__ method took a path to the file it was meant to represent
But there were a few times where you'd make the list manually and then wrap it in that class
So the __init__ method was changed to type check what it passed to it and just accept the list as an instance variable if it was a list, or read a file and create the list if it's a string/PathLike
So in retrospect, I would have rather had a class method for whichever of those two cases we'd decide is the odd one out.
Oh, yeah... I have to deal with that crap in apraw.Reddit, too. I just use a ton of if-statements. I like how Kotlin and C# support both overloads and default values.
It doesn't make a whole lot of sense for Python to support overloading since the signatures are untyped
class A:
def __init__(self, one, two):
self.one = weird_func_one(one)
self.two = weird_func_two(two)
@classmethod
def special_case(cls, special_value):
"""Never calls A.__init__ :O"""
new_obj = super().__new__(cls):
new_obj.one, new_obj.two = weird_function_three(special_value)
return new_obj
It could be argued that A.__init__ shouldn't be written that way
this is just an example. We'll assume that there's some case where it makes sense for A.__init__ to be that way
So what I'm wondering is, what issues could arise by totally circumventing the init?
I didn't really look into the discussion, but I see no reason to support overloading simply because of A) the nimble use of *args and **kwargs in the language and B) classmethod constructors
@open trout I'm specifically interested in classmethod constructors that, instead of converting their own arguments into values that can be passed to the __init__, totally circumvent __init__
Ah I see, but why would you want to circumvent it?
in case someone ever thinks of a situation where trying to map the inputs to valid arguments for __init__ is inelegant.
So __mro__ is literally just an inheritance path from the current class to object?
yeah basically
Oh sick I finally understood it 🙂
!e
class A: pass
class B(A): pass
print(B.__mro__)
@north root :white_check_mark: Your eval job has completed with return code 0.
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
it's just a tuple, starting with the current class and ending with object
Can I overload mro with non class objects?
so what are the new features coming to Python that everyone is so hyped about
!pep 622
This primarily, and the new parser I think
if I were to create a function metatype, how would I create instances of it?
I guess you could make a decorator that takes the __call__ attribute of the function and gives it to a function of the special metaclass?
What do you mean by "function metatype"? Can you better explain the problem you're looking to solve?
what does -> do?
in C/PHP, attrib lookup, not sure it has a use in python?
Return type hinting
@silk sorrel It's used in function annotations to annotate the return value
This question is probably better suited for #python-discussion
That makes sense. Thank you!
oh right, type hints..
im using them more and more, but couldn't recollect the context here
back in my day people used docstrings 🧓
Speaking of docstrings...
What's the go-to for having decorators for classes and preserving __doc__ as well as __name__?
I doubt functools.wraps() will work in this case?
What's your decorator returning? A new class object or a function object?
I don't think wraps works when applied to a type instance (class object), but it should work for a new function
A new class. A wrapper class to be specific that inherits from the given class and just adds some extra functionality. 😄
Hmm
Interesting
Not sure how to best approach this. You could get it to work with the type constructor, but that's a bit less readable
!e
def decorator(cls):
def other_method(self):
print(f"The other method was called on {self}")
new_cls = type(cls.__name__, (cls,), {"other_method": other_method})
new_cls.__doc__ = cls.__doc__
return new_cls
@decorator
class Foo:
"""This is a nice docstring!"""
def method(self):
print(f"Called method on {self}")
print(Foo.__doc__)
print(Foo.__mro__)
f = Foo()
f.method()
f.other_method()
@wide shuttle :white_check_mark: Your eval job has completed with return code 0.
001 | This is a nice docstring!
002 | (<class '__main__.Foo'>, <class '__main__.Foo'>, <class 'object'>)
003 | Called method on <__main__.Foo object at 0x7f19643d30a0>
004 | The other method was called on <__main__.Foo object at 0x7f19643d30a0>
Is there any reason for "delaying the inheritance" by using a decorator?
Also, this probably reverses the MRO (it places the additional class before the original class), so not ideal
Yeah, but why not just have an inheritance/mixin structure?
Hmm... I suppose it's because I want to make my library as easy as possible to use and I feel a mixin could have weird side-effects.
What I'm trying to achieve is this:```python
from reactive import all_reactive
@all_reactive
class Foo:
def init(self):
super().init()
self.name = "Foo"```
So the decorator looks like this:```python
def all_reactive(org_cls=None, only_type=None, not_type=None):
if org_cls:
class AllReactive(org_cls, ReactiveOwner):
def init(self):
super().init()
self.__only_type = only_type
self.__not_type = not_type
def __setattr__(self, name: str, value: Any):
if not isinstance(value, ReactiveProperty) and not name.startswith("_"):
if self.__only_type and not isinstance(value, self.__only_type):
return super().__setattr__(name, value)
if self.__not_type and isinstance(value, self.__not_type):
return super().__setattr__(name, value)
try:
value = ReactiveProperty(value, name)
except TypeError:
pass
return super().__setattr__(name, value)
return AllReactive```
out of curiosity, what does your lib do? And what does reactive/all_reactive do?
why is that class in the function aswell tho?
oh yeah just noticed that, that's so trippy
like that can be moved out side of that function and replaces with a __new__ method no?
out of curiosity, what does your lib do? And what does
reactive/all_reactivedo?
@open trout oh I'm actually happy to show this off because I have no clue if it's any good, but I like the idea and was hoping for some feedback anyway! https://github.com/Dan6erbond/ReactivePy
oh yeah just noticed that, that's so trippy
@open trout I wasn't sure how to have the dynamic inheritance...
There's probably a ton I could do to optimize the codebase to be honest. :P
It's so far just a bunch of hacks put together in a so-called "library".
Wow, that sounds cool! Good luck with it!
is there a python equivalent of javascript's module.exports?
i have to import a lot of stuff from a file and i don't feel this is right
oh, you can import the module itself
import module
or
import package.module
or
from module import cls, func
....
__init__.py IMO is so much cleaner than the module.exports in Js.
But I personally also just hate ES5 modules.
Isn't it just export now instead of module.exports?
commonjs and es6 stuff
require() vs import <> form ""
https://hastebin.com/genibubadi.py
i have to import all of the instances and importing usingfrom schemas import *looks very messy
well if you have to import everything, and use it in the same namespace, that's the way to do it
you can import schemas, and then just call it like schemas.json() or w/e
i need to use them in several different files and i'm just looking for the most efficient way of importing them all
well, efficient and cleanest
Wow, that sounds cool! Good luck with it!
@open trout thanks! I'll be using it in aPRAW soon to get an idea for how it works in a production library. (:
ayy :^)
like that can be moved out side of that function and replaces with a
__new__method no?
@radiant fulcrum could you explain further please? O.o
I got a rough idea of __new__() but apparently not good enough to understand how it would be useful here.
So I'm trying to get new to work now... Is this correct?
class AllReactive:
def __new__(cls, org_cls):
return type(cls.__name__, (ReactiveOwner, org_cls), {"__doc__": org_cls.__doc__})```
can any one help me [ return " ".join(final) ] ---> what is this ---> " ". what does this mean ?
If you have a list of strings, they will be joined by whatever is specified before calling join() since join() is a function on the str type. Like so for example:
l = ["str1", "str2", "str3"]
print(" ".join(l))
#bot-commands
@shy belfry Very Good. Thank you. Got it Now.
is it common for them to add new reserved words to python? just found out about async via it breaking things
it is quite rare, but does happen sometimes
I don't really understand the new words, was curious why they added them
async/await were added in Python 3.5 to have better support for asynchronous programming/coroutines
They became reserved/keywords in 3.7, I think
The only additions between 2 and 3 seem to be the singletons and then async/await ( + removal of exec)
so really not many changes there
oh and print was removed
removed as a reserved word?
yes
Because it was a statement before,
Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print = 5
File "<stdin>", line 1
print = 5
^
SyntaxError: invalid syntax
that seems an interesting choice honestly
well, I have a lot to go learn now, hadn't heard of singletons before and async seems kind of cool
Will converting python files to .exe increase performance or have any benefits over just python files?
If anything it makes them slower (the times I have frozen scripts, at least)
The numero uno benefit is just portability
Ok thanks 😊
@karmic slate unless you use something like nuitka (transpiles Python to C and compiles the C), it will be slower
Okay thank you
hey since i from a java background, is there sth in python that is equivelent to private, public and protected?
not really
other than naming conventions
_ prefixing the var name normally means it is a private varible
all caps normally means its a constant
Not in the same way. The philosophy in Python is that "we're all consenting developers", although there are some conventions to indicate that some attributes are part of the internal implementation and you should mess with them at your own risk.
That's the single leading underscore (_) as mentioned above
There's also the double leading underscore variant (__attribute), which adds another layer of "you should really think twice about touching this" by slightly mangling the name of the attribute in the external view of an object. (The name of the class gets prepended.)
It's not meant as absolute protection/security, though; more as a safety cap on a button that you need to take off before you can press it: Are you sure you want to touch this?
intresting
you can sort of make constants by using frozen sets
The main purpose of the mangling is to prevent taking up names from subclasses, since we can use the _ prefix to mark it as "private"
but normally everything is based of the general nameing convention of pep8
The main purpose of the mangling is to prevent taking up names from subclasses, since we can use the _ prefix to mark it as "private"
@peak spoke
Yeah, that's true
and im assuming namespaces also prevents what ur saying as taking up names right
This is a good post on underscores in Python: https://dbader.org/blog/meaning-of-underscores-in-python
and im assuming namespaces also prevents what ur saying as taking up names right
@unkempt rock
Kinda, but this is more for (multiple) inheritance, where you extend the functionality of one class with others
also touched upon here https://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers
@unkempt rock You might also be interested in the @property decorator in Python. The default assumption in Python is that you don't need to wrap any layers around instance variables, but if you have a circumstance where you feel it's needed, @property lets you do it while ensuring that accessing (and changing) those attributes has the same syntax as regular access.
The dataclasses module that comes with >=3.7 also lets you make frozen instances where the process of changing attributes of an instance is really convoluted.
@wide shuttle tx im still trying to break some of my 'java' habits
hey, little question regarding dicts; from which version is dict order guaranteed?
Is there anything to read up on for how string interning works on cpython (or in general)?
I've got roughly 75k dict items which share a few short strings as their attributes, the values of the first string attribute also exist as dict keys and seem to be interned, but then the second attribute which contains strings is an unique object for every item
@cloud crypt 3.6
3.6 as an impl detail, 3.7 language spec AFAIK
Oh it was spec in 3.7?
https://discordapp.com/channels/267624335836053506/709904092280914030/716996191174262856@peak spoke was discussed before
