#internals-and-peps
1 messages Β· Page 48 of 1
Usually easier to just subclass UserList etc. with design and behaviour
@lost nexus the problem with subclassing builtins like that is it is easy to slip back to a real list: l = MyList(); l = l[:3] # oops, l is list, not MyList
I see
Please read the channel description @unkempt rock
This is a discussion channel, not a help channel
Hm, maybe it's possible to make a member deriver.
Oh, I'm talking about the inheriting list problem
If you want help with a specific question, check out #βο½how-to-get-help. This is not a help channel
Event: ???
@derive
class MyList1(list):
# slices return MyList instances
pass
@derive
class MyList2(list):
# slices return MyList instances
# `update`, `__add__` and `__iadd__` are redefined to use the new `append`
def __init__(self, iterable):
self.container = list(iterable)
def __setitem__(self, index, item):
self.container[index] = item
def append(self, x):
self.container.append(x)
H m m
UserList is slightly more useful then subclassing since it always wraps the result to the subclass (via self.__class__)
Will it work correctly if I implement, say, an immutable linked list?
How come dict.keys() returns KeysView[Optional[key_type]] rather than KeyView[key_type]?
Or, at least, mypy seems to think so.
Oh, nevermind, it was just the type inference acting up.
ah
Typeshed has KeysView[_KT]
Yeah, it wasn't an issue with the return type, it was mypy inferring an optional type on the result of a dict comprehension.
def whatever(
...
) -> return_type:
...``` _no return type of the func_
In my code.
and I donβt want to fix my code just by # type: ignoring all its mistakes
Sometimes, although in this case it was actually correct and it was my fault.
indeed, but I have shown an example that makes me wonder above
ever tried to make a function that takes str and bytes and calls their methods? thatβs helly
well unless you use typing overload
honesty i have p good experience with mypy 90% of the time
How do i make an os with python?
What are functions Annotations?
I recently been trying to learn a little bit of functional programing in python and I came across the word annotations. After searching and watching few videos I still didn't get a clear view of what are the function annotations and why they could be useful in python. I'll be very thankful if you guys answere the following questions in a simple way to let me get a better understanding of it.
- What are functions annotations used for?
- What will it effect on my functions parameters if I used them in function?
- Does they effect in any manner at my function?
I'll be really happy if you guys could explain these to me or maybe share some youtube videos which help me understand these.
Thank you so much.
- They are the groundwork on which type hints are born. A way to add additional info about parameters and return values
Can anyone suggest me a good python machine learning tutorial?
- nope, as annotations are optional
See on udemy
Which means, the big thing is this: function annotations do nothing for the code execution. They're mostly there for the humans who are reading the code
even though there are static type checkers like mypy, which is their de-facto
Once that part clicks, the rest is easy to understand
you can hook your function to dynamically check inputs based on annotations, but that's just ew
you can have use of annotations like discord.py does, though
So 2. And 3. Are nope in native python. You can have libraries or programs built on top of it that tries to turn them into something more, as nekit mentioned
But keep them aside when you first try to comprehend function annotations themselves.
Their only effect is that they're added to the __annotations__ attribute
also annotations can be used in order to create something like a dataclass
yeah
I once wrote some thing for ctypes with it ```python
from ctypes import wintypes
import ctypes
kernel32 = ctypes.WinDLL("kernel32")
@func_def(kernel32.CreateToolhelp32Snapshot)
def create_snapshot(flags: wintypes.DWORD, process_id: wintypes.DWORD) -> wintypes.HANDLE:
pass```
which sets the argument/return types for DLL function in order to make calling it simpler
~ Finally read about descriptors in python, haha ~
yesterday i checked out function scopes and global etc
i'm mainly using pandas, and when i change outer df in my functions it actually changes
shouldnt it be changed at all in the end?
im confused
can you show an example?
I got it now so basically they are the hints for human. To better understand what types of value function will take and what it will return.
I was thinking its somekind of way to make functions take only a specific types of values but I was wrong as that is not the case
They are used by mypy, which is a tool that statically checks that the types are correct
But it doesn't enforce anything at runtime
@cloud crypt i'll post now, one min
df = pd.DataFrame([0,1,2,3])
0
0 0
1 1
2 2
3 3
def example(df):
df.iloc[0] = 99
return None
example(df)
df
0
0 99
1 1
2 2
3 3
@cloud crypt
what's confusing in it
ah
well
DataFrame is mutable
and you mutate the object
this has nothing to do with scopes really
lemon = [1, 2, 3]
def append_n(some_list, n):
some_list.append(n)
append_n(lemon, 4)
print(lemon) # [1, 2, 3, 4]```
so scope is just for variables?
protected that way
so... global keyword is just for variables in order for them to be manipulated?
Yes. Variables are names of objects and are affected by scope. Objects themselves are not
hmmm, good to know. i was always worried if my pandas object would be changed or not when entering a function
if i dont want them to be changed, then using .copy() would be a good practice for me
when passing in funcs
thanks @cloud crypt @flat gazelle
well functions that change the object's state could be owned by the object
you guys are talking magic
to be a safe copy, you would need to do a deep copy. I think that is costly
is pycharm a good text editor for python beginners?
@tacit hawk yeah deep copy but some computational stuff needs to be done in a big dataframe, so i have to use copy of a section to do various stuff
some of them might change the original, that's what i'm afraid of
@tacit hawk ide is like a tool kit and one of the tools is a python compiler??????
Idk if pycharm installer comes with python or you need to install it. But yes, IDE is a collection of tools that helps you, it is not just a text editor
If I recall, pycharm comes by itself. You install Python, then you tell Pycharm where it is.
I apologize if the above information is inaccurate. I don't use Pycharm anymore. I now use NotePad++ then use Powershell to compile and view the output.
It took a bit of setup and I had to learn some Powershell syntax. It was a bit of a pain initially, but after I used it for awhile, I don't think I wanna go back to an IDE except for debugging or other resources.
Hello, im a student trying to learn python by myself. I have worked with Flask, Docker, REST API + Postman, MongoDB, PostgreSQL , automatic tests and doing DJANGO project now. Are there any other popular libraries/ solutions worth learning?
Props to you. You've gotten your feet wet in more things than I have. As for things "worth learning", I just go with what interests me. I'm not too familiar with the trends of the industry, even though I probably should be.
Thanks, could you give some examples? Might be interesting for me too
do lots of little projects that interest you
new apis and maybe some new ways of thinking you'll have to encounter
Check stack overflow surveys
Then go after what's popular if that's what you are after for
Hello, im a student trying to learn python by myself. I have worked with Flask, Docker, REST API + Postman, MongoDB, PostgreSQL , automatic tests and doing DJANGO project now. Are there any other popular libraries/ solutions worth learning?
@crisp wharf By automatic testing do you mean pytest and unittest?
@crisp wharf have you deployed to production before?
this is off-topic for this channel, however
@tacit hawk you can't copy matplotlib axis objects - not sure if you're aware of why that is?
i tried recently with deep copy, and it failed, so you saying that above reminded me
No I am not aware, I don't know that lib
I've an idea
I want to build an fps counter
Do you guys have any idea on the best way to capture the frames of the display?
What I'm thinking is to capture 1 pixel from the screen using opencv, is it efficient idk, maybe?
What I'm thinking is to capture 1 pixel from the screen using opencv, is it efficient idk, maybe?
@night patrol maybe more than one
what if the pixels stay the same
@night patrol This is not the right channel for this (read the channel description). Check out #βο½how-to-get-help
uh hmn. so, back before delayed type annotations, you could pass in functions as type annotations
but now they're strings & the suggested method to get objects back from annotations is eval, which doesn't seem to be cooperating easily with functions
so my question is, is there a convenient means of embedding functions into delayed annotations
and/or get a function back via eval()
oh hmn okay jk apparently annotations take care of all of that if you pass in the annotation as a string
...weird
i guess pycharm just hasnt gotten the linting down for that yet
https://www.python.org/dev/peps/pep-0563/#non-typing-usage-of-annotations
uses for annotations incompatible with the aforementioned PEPs should be considered deprecated.
With the aforementioned PEPs referring to using annotations to provide type hints. By my reading, using annotations for purposes other than type hinting is deprecated.
im not sure what "incompatible with PEP 484" would mean
presumably some of the experimental libraries that use type hints for runtime validation
@raven ridge is what one would think, but pep 593
so 3 years ago maybe
but given pep 593's acceptance, runtime annotations are back on the menu
is there a max amount of references that an object can have?
probably until you run out of memory
https://github.com/python/cpython/blob/e9684fac5a158be9806304a676e619857520a4dc/Include/object.h#L107 - on a 64-bit build of CPython, a Py_ssize_t maxes out at 2**63 - 1. So, one object maxes out at 9,223,372,036,854,775,807 references.
haha alright
Which is also the maximum amount of addressable memory, so you'll hit the OS ram limit before being able to have that many objects to reference it from.
Technically it's one byte less than half the maximum amount of addressable memory, and technically it's possible to add a reference without using any additional memory.
It's possible to reach that max reference count without running out of memory first, though very very unlikely. Absent a bug, it would require externalizing pointers out of the process with the intention of reading them back in later for the decref call, or something like that.
But I wouldn't be shocked to learn that Python doesn't guard against that, since you have to really be doing something weird (or forgetting decref calls, meaning you have a bug) in order to get that to happen
Indeed, CPython doesn't bother to guard for overflow. https://github.com/python/cpython/blob/e9684fac5a158be9806304a676e619857520a4dc/Include/object.h#L427
!pep 611
This PEP is about adding a one million safe limit to most things in the interpreter
I've been looking into https://www.python.org/dev/peps/pep-0518/ recently (pyproject.toml) and came across a blogpost by Brett Cannon about the subject. There's nothing really groundbreaking in the post, but it's nicely written and provided a coherent story on the why and what: https://snarky.ca/what-the-heck-is-pyproject-toml/
Recently on Twitter there was a maintainer of a Python project who had a couple of bugs filed against their project due to builds failing (this particular project doesn't provide wheels, only sdists). Eventually it came out that the project was using a pyproject.toml file beca...
Hey, @magic junco, this is not a help channel, but rather a discussion channel to discuss Python itself, from higher-level perspective. We do have help channels and you can claim one for your question (see #βο½how-to-get-help). Sorting algorithms also sounds like something that could fit in the #algos-and-data-structs topical channel.
oh, sorry about that
can we get switch-case with python 4?
!pep 3103
Guido is adding it in actually
Status : Rejected
Probs- wait what
Ah that's true
I wonder why LL(1) can't parse it, the proposal seems to be parsable
https://github.com/python/cpython/commit/b45af1a5691e83b86321fc52d173f66cf891ce5f
https://youtu.be/QppWTvh7_sI?t=2510
Parsing Expression Grammars (PEGs) are a relatively new formalism for describing grammars suitable for automatically generating efficient parsers. I've become interested in using a PEG-generated parser as an alternative to CPython's nearly 30 year old "pgen" parser generator. ...
match statement may be more powerful than switch case
match is cooler yeah
idk really since i didnt even know anything about it
match [1, 2, 3]:
case [1, 2, a]: print(a)
case [*b]: print(b[1])
``` maybe
or maybe a less powerful form
full pattern matching seems a bit unneeded
typo in match
ty
is there any way to create my own low level programming language?
thanks in advance guys
not quite related to this channel?
i dont have any idea of this topic
also what do you define as low level programming language
well not as high as python is pretty much most of the languages
whatever
is there any way to?
@unkempt rock I'd look into this https://craftinginterpreters.com/
question is why, and you wouldn't want to use python for that unless it is a toy language or something
Most boring, useful languages are written in C.
and looking forward
i just want to experiment on something different rather than taking my personal projects in python
honestly, high level languages are easier, because you can avoid LLVM/ASM and just interpret. Compiling things is not too easy, though you can compile to scheme to save effort (idris 2)
oh so you mean that making high level language is easier and efficient ?
not sure about efficient
ohh then whats the way?
depends on what you mean about efficient
efficient in sense like python's maplotlib and seaborn libraries
it only takes a couple lines
Efficient to write normally trumps efficient to run
but the output is big
But length of code isn't really efficiency
Are you talking about shortness of code or execution speed
yeah kind of
shortness of code
That's not a great thing to optimise
do you want to write a lang in few lines, or a lang that needs little code to do things
By all means avoid unnecessarily writing stuff people have written before
a lang with little code
But trying to reduce character count is pointless and normally harmful
ohh
yeah, do not do that
then what about making a lang like c?
I think we've strayed a bit from the topic of this channel.
Yep
then is there any other channel for this particular topic?
ok thanks for the help i will post there
Hello fellow Pythonists! I just wanted to ask whether it'd be a good idea to create a tunnel between one of dedicated channels and Stackoverflow Python chat?
as a pythondiscord server idea?
@crisp wharf have you deployed to production before?
@north root didnt get notification, what do you mean?
or as your own personal project?
@crisp wharf By automatic testing do you mean pytest and unittest?
@unkempt rock Pytest and mocking for now
@stable grail As a pythondiscordserver idea
so im personally not sure how we could moderate such a feature. but any pythondiscord ideas can be brought up in the channel for it, its called #community-meta
its a channel made for these kind of discussions
Hi. I wanna make a project with using google maps or normal maps. when i click to any country i wanna get some info about that country from the data base. basicly i will click to africa contenent and program will show what is the pop currency and more
what part of that requires google maps?
you can just draw a map with python3, have a clickable area on each country, and if you click it, it will show you the info stored in your db?
which lib i can use for this
any of these
(for the display part - you need something for your database too - probably start with sqlite3? (or json if you don't want to learn sql)
def acquire(self, blocking=True, timeout=-1):
me = get_ident()
if self._owner == me:
self._count += 1
return 1
rc = self._block.acquire(blocking, timeout)
if rc:
self._owner = me
self._count = 1
return rc
__enter__ = acquire
i had no idea you could do this
Could do what?
the __enter__ thing
Think about it from another perspective, would you be surprised if you saw this at the module level?
def function():
return "some return"
some_name = function
i think 'sickened but curious' is the correct reaction.
Yeah, it's mainly to bridge towards that this works the same within the context of a class definition
It's only that the eventual names end up as class attributes instead of module-level names
A def statement still does the same thing: it creates a function object, then assignes a name to that function object so we can use it
The only difference is that when that happens within the context of a class definition, assignments end up as class attributes
name = [1, 2, 3]
def function():
pass
class Foo:
name = [1, 2, 3]
def function():
pass
what is quite interesting
In [14]: class O:
...: def __int__(self): return 4
...: as_int = int
...:
In [15]: O().as_int()
Out[15]: 0
In [16]: class O:
...: def __int__(self): return 4
...: as_int = lambda self: int(self)
...:
In [17]: O().as_int()
Out[17]: 4
In [18]: l = lambda s: int(s)
In [19]: class O:
...: def __int__(self): return 4
...: as_int = l
...:
In [20]: O().as_int()
Out[20]: 4
It's because int does not have a __get__
So, in your first example, you don't get a "bound method"
You just run int() straight without arguments
With gives you a 0
It's not the definition that does anything special for "methods"; it's accessing them
The descriptor protocol ensures that the object gets passed as the first argument by binding it to the callable
That's what "creates" the bound method from the function object
As int does not have a __get__ method, no such binding happens and the object does not get "bound" to int
You just get int back directly when you access the attribute
In the other two cases, you bind the class attribute to a callable that does have a __get__
interesting
!e
def perfectly_usuable_as_method(self):
print(self)
class Foo:
method = perfectly_usuable_as_method
f = Foo()
f.method()
@wide shuttle :white_check_mark: Your eval job has completed with return code 0.
<__main__.Foo object at 0x7f11e40af9d0>
It's not about the place of definition of the callable
A def statement (and a lambda expression) just creates a function object and assigns a name to that function object
Whenever you assign a name in a class definition, that name just happens to be a class attribute
So, there's nothing special at definition time (edit: removed something from this message that had nothing to do with this to avoid confusion)
The binding of the object happens at attribute access time
It's just that a def statement "hides" the fact that these two statements are very similar:
name = "something"
def name():
pass
Both create an object, and then assign a name to it
In R, a function definition is less appealing from a readability perspective, but does make this assignment more clear:
name <- function() {
print("hello!")
}
Where you see <- just think = (which is also valid in R, but makes the style zealots of R scream)
You can even get bound methods from a function without ever assing a class attribute to a function
!e
def my_pseudo_method(self):
print(self)
print("Function object:", my_pseudo_method)
bound_method = my_pseudo_method.__get__("Hello, world", str)
print("Bound method:", bound_method)
bound_method()
@wide shuttle :white_check_mark: Your eval job has completed with return code 0.
001 | Function object: <function my_pseudo_method at 0x7f0244559dc0>
002 | Bound method: <bound method my_pseudo_method of 'Hello, world'>
003 | Hello, world
(and obviously self is just the conventional name)
what's the stacktrace with respect to python debugging?
wow i started a whole discussion and missed all of it :/
It was mostly me talking to myself
how I would do this is to make the decorator store the function in a list
so I recommend making it as part of a class
function_object.__name__
can I ask what you're trying to achieve @unkempt rock?
and also this channel is for discussion about python itself, for help read #βο½how-to-get-help
while func(): continue or while func(): pass?
neither?
why not?
because it'll eat up your cpu
oh yeah but apart from that?
"pass", but what's your real func() do?
idk it turned hypothetical
originally was for a coroutine, but realised i should put asyncio.sleep(n) there instead
How is argument passing handled in py, does it make a new copy everytime?
No, the opposite. The names get assigned directly to the arguments that are being passed
There's actually a great video about it on YouTube
"Speaker: Ned Batchelder
The behavior of names and values in Python can be confusing. Like many parts of Python, it has an underlying simplicity that can be hard to discern, especially if you are used to other programming languages. Here I'll explain how it all works, and pre...
This explains the basic idea behind how names and values work in Python
It also goes it into what happens when you pass arguments to a function
time to watch, thank you ! π
Is there a way to get the opposite of a slice in python? I have a list of dictionaries and I'm trying to find out how to find what the [int] would be for a specific one.
The docs https://docs.python.org/3.7/library/time.html?highlight=time monotonic#time.monotonic of time.monotonic says only the difference between consecutive calls are valid, that means
start = time.monotonic()
time.monotonic()
end = time.monotonic() - start # invalid difference
?
No, it means that there's no absolute reference point, so the size of the numbers you get by themselves doesn't really mean anything
but the difference between the numbers does. In this case, the calls are all consecutive to each other (following each other in a continuous manner)
im trying to learn how to work with sqlite, what should i try to make? like a mini project i mean
try making an atomic queue with it π
what is that
can someone helps me? i am trying to do a welcome/auto-role commands, but them are the same here:
like wait in queue to get in a match
yeah - so you have pop and push, push pushes an item onto the end of the queue, pop removes an item from the front of the queue
what is this about
not a queue like in overwatch or something
well conceptually in that it's a list of things
but not specifically that
oh i see i thought you were explaining the concept of a queue in multithreading
ignore me
i dont know what are we talking about anymore
it's a list, you can only add on the end, and remove from the front
we call it a queue
i just want to do someone with sqlite
lmao
something* haha
ive done tons of things
i just wanna do like anything with sqlite to understand it a bit better and then replace my json database with sqlite for my discord bot
i still think an atomic queue in sqlite was a good idea π
why don't u use the project of converting your json database to sqlite to understand it better?
u mean go right to my main goal
yeah might as well
you can always ask people to look at it, and help you along the way
but i really dont know that much
tbh i know barely anything about it
help pls
bruh
and the error is clear
ur redefining what u already have defined
best way of learning is pushing yourself, and having someone help you π€·
Bande de fdp
and how i can do to have the welcome message and the auto-roles in the same .py file?
just like for example taking the input, storing it inside the database and then retrieving it and printing it out
@unkempt rock #βο½how-to-get-help We also have a dedicated #discord-bots for discord.py questsions
the following:
@attr.dataclass(frozen=True)
class blah:
x: float
y: float
x = blah(1, 2)
type(x)
returns __main__.blah, I'm wondering what would be the most typical way to document this in a doc string
i have a function that takes this as input
takes a blah?
yes
you can typehint with a custom class
there's a nice standard way of doing docstrings for argument types
what's the standard way, I'm not using mypy or anything
this is how pycharm likes it and it's fairly common
you can still use typehints to document the code
looks kinda rst ish, i tend to use similar structure
but I don't know what i'd write, if i have
def foo(x, y, blah_obj):
'''
Args:
blah_obj( __main__.blah): blah obj with x, y values
'''
just this i guess π€
yeah that should be fine i think
__main__ looked weird to me for some reason
eh just say blah
__main__.blah is just trying to give a nice way of describing where it is
like if your package is called fooblifier
i'd say the argument type should be given as fooblifier.Blah
or just Blah
i've never used the package like that before
perhaps it's similar to pd.DataFrame though
sorry?
putting the package name in the docstring for namespacing like that
kinda makes me wish that fstrings worked as docstrings
def foo(x, y, blah_obj):
f'''
Args:
blah_obj( {__name__}.blah): blah obj with x, y values
'''```
*this doesnt work cause of how docstrings are handled internally*
cause then that would work
Something along the lines of
class Sample:
__doc__ = f'''
haha yes hello I'm a doc string
'''
``` should work, but that's for classes, functions will just be a pain
yea that would work for classes
i think matplotlib has a bunch of autogenerated stuff π€
def func(): pass
func.__doc__ = f'''My doc f-string''' # ew```
this? idk what that decorator does
that prob copys the docstring from Figure.text and sets it on figtext if i had to guess
Looks like it copies the docstring from Figure.text and puts it as the function's docstring
# Allegedly similar to this
def copy_doc(source):
def actual_decorator(func):
func.__doc__ = source.__doc__
return func
return actualy_decorator```
is this common? Or a mpl thing
mpl seems like it's a bit of a mess, i tried to copy an axis object the other week and got no where
I haven't encountered docstring.copy personally, but it sounds like something that would be common
I could see it being a part of functools
is there a good reason why __copy__ and __deepcopy__ are missing from https://docs.python.org/3/reference/datamodel.html#special-method-names ? is this a documentation bug?
@pliant tusk they cant work as docstrings because then you'd have to execute the function to get the docstring, which would be a huge mess
i mean, that makes sense
@paper echo It's not really something that's defined on a lot of objects and relies on a module (excluding the copy methods on mutable sequences etc), they are documented under https://docs.python.org/3/library/copy.html although it's not in the regular method -> description format
@peak spoke do you know why one wouldn't be able to copy an object? I tried to copy a matplotlib.axis object and it didn't work, and i don't really understand why
seems that it should just be some thing in memory? Why is copying some things ok but not others π€
I don't know about the axis, but it can have data that is not copyable (doesn't make sense in an another object), depend on external connections like callbacks etc. or the behaviour is just not defined for it as it didn't seem necessary
i wanted to copy so that i could have functions that worked as typical functions, instead of loads of global state
but yeah, no idea
@peak spoke yeah but "this is rare" isn't a good reason to omit a special method name from the special method name docs page
All of those methods can be accessed directly through basic python syntax or are used somewhere along the way to emulate types etc. while the interaface of the copy methods is the copy module
@magic python btw, don't use that ":param:" style of docstring. it's gross, and there's a better standard format.
@spark magnet π I don't use that
"""
Args
foo (int): thing
bar (float): something else
"""
is what i go for
There are a few more dunders that are used by modules like that, like pickling
Is python handling elif and else: if: differently ?
nope, behaviour should be exactly the same, however i have no idea about execution speed
if you're just asking about basic behaviour
They both get parsed to the same instruction I believe
@final whale they are the same
thought that py would parse them differently
thank you Seagull, Numerlor and Nedbat π
could you always access class attributes through self?
I'm not aware of any version where you couldn't.
i swear pycharm always used to get mad at me for it
i'd like to make an infodecorator class for people to use and me to use
should I try something like this
@InfoDecorator
class myDecorator:
x: List[int]
y: Optional[int]
for decorator creation
or more like a namedtuple
myDecorator = infoDecorator('myDecorator', 'x y', defaults = {'y': None})```
to be used like this
def somefunc():
pass
print(somefunc in myDecorator) #False
@myDecorator([1, 2, 3])
def otherfunc():
pass
print(otherfunc in myDecorator) #True
print(otherfunc.x) #[1, 2, 3]
print(otherfunc.y) #None
And why is it a decorator?
@grave jolt I figured that would be the best way to add information to functions
I can decorate it with the decorator and I'll still have a callable object but with extra useful properties
Well, that's very similar to a shortcut to a class creation
Maybe make myDecorator a class factory
And then check membership with isinstance, as with namedtuple
do submissions take a while to appear on the python mailing list? i sent an email to a list i'm subbed to, and can't see it in the archives or under my posted, and haven't received a response/confirmation :/
Which list did you send something to?
python-ideas
as far as I know, that list isn't moderated up front other than that you need to be a subscriber
but I'm not exactly sure
Hmmm... can u check if you can see my question?
I don't know what you sent
It has my name on it tho (eventfd stuff is what I sent)
One of the things I really wish Python had was better anonymous functions
But they will probably never be added
There are a number of reasons for this but I would quite like the feature
Although I know it won't be added
Lambdas are unreadable and not powerful for a lot of Python tasks currently
I think you showed me a use case for more powerful lambdas before
but, I haven't really seen the use of them in practice
yeah, but it's a rare one
I'd very much prefer regular def statements for functions
I'd refer using them for event handling
And I fear overuse and unreadable code, almost to the point of javascript
Considering you can define functions inside functions, are lambdas really needed for anything other than conciseness?
Isn't Lisp more oriented for Lambda expressions? (I'm not that versed, just that i knew somebody who was really into it and tried teaching me a bit)
handle.event(2, message => (
if True:
print(3)
))
Which I think is the prime example of allowing for unreadable anonymous function chains
they are nice for event handlers and that is pretty much it
And in cases where you want to group them inside objects
and you can do that with decorators
If I wanted to make a class with a callback, anonymous functions are a good way to go
python really does not like callbacks
I prefer anonymous callbacks
iirc lambdas can't be used when scheduling callbacks for Kivy
I wish they would be added to Python but they won't be
Can lambdas store local variables? (Be a closure or whatever)
sort of
lambda: (
x := 1,
print(x)
)
so, yes @red solar
but they don't work with nonlocal or global or etc
and this is getting #esoteric-python
Whatβs nonlocal? Thread local?
a = 8
b = lambda: a
c = lambda a=a:a
a = 9
print(b(), c()) # 9 8
you could also use def here
Can lambdas store local variables? (Be a closure or whatever)
this was the question
it wasn't about defaults and variable getting
But anyways, lambda power would be a useful change to me
this is what a closure is though...
feels kinda cheating, storing the variable as a default param
That's true
@red solar There's a better and more clear way
lambda: (
x := 1
)
But lambdas that do this aren't pythonic
that does something entirely different
It still stores a local variable though, right?
Whatβs nonlocal? Thread local?
@red solar
No, nonlocal is for names in the nearest enclosing scope that is not the global scope. You usually see it in things like decorators where you define a function within a function:
def outer():
counter = 0
def inner():
nonlocal counter
counter += 1
but he was asking about closures, and := is not really useful for closures
I don't interpret it that way
I'm interpreting Can lambdas store local variables? (Be a closure or whatever) as Can lambdas store local variables? (Through closures or some other method)
sorry i asked that badly, i meant through clojures but my mind had a brain freeze and i wasn't sure if clojure was the right term
clojure is not, closure is
*closure lol
there is no neater way that I know of to capture the value of an outer variable
Lisp and raku do that by default, but python resolves names when the function gets called
but also why? just don't define it locally before you use it
@red solar nonlocal let's you rebind a variable in an enclosing scope to a new value. Without nonlocal you can read or modify an object from an enclosing scope, but not assign to it.
@red solar Take a look at this very naive decorator:
!e
def count_calls(func):
counter = 0
def wrapper(*args, **kwargs):
nonlocal counter
counter += 1
print(f"This function has been called {counter} times")
return func(*args, **kwargs)
return wrapper
@count_calls
def foo():
print("Running foo!")
@count_calls
def bar():
print("running bar!")
foo()
foo()
foo()
bar()
bar()
foo()
@wide shuttle :white_check_mark: Your eval job has completed with return code 0.
001 | This function has been called 1 times
002 | Running foo!
003 | This function has been called 2 times
004 | Running foo!
005 | This function has been called 3 times
006 | Running foo!
007 | This function has been called 1 times
008 | running bar!
009 | This function has been called 2 times
010 | running bar!
011 | This function has been called 4 times
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/ikomuwiwuy
We don't want to redefine counter each time the wrapper/function is called, since we need to keep a count across calls
ahh ok i see - kinda seems like static local
but ok that use makes sense
Completely forgot variable name shadowing was a thing in python
Why doesn't counter get garbage collected there
What's the reasoning behind there still being a reference to it
Is that just how decorators work
The inner function holds a reference to the nonlocal object in its closure
Otherwise, decorators couldn't work at all (if you think about it, the function that was passed in, func, also is nonlocal to the inner function)
!e
def outer(func):
def inner():
print(func)
print(inner.__closure__)
@outer
def some_function():
pass
@wide shuttle :white_check_mark: Your eval job has completed with return code 0.
(<cell at 0x7f5b551749d0: function object at 0x7f5b55120e50>,)
Typically in one-off function calls that take a key parameter
i'd say in any place where you are not going to use the function more and once
like pure says a one off
@unkempt rock A lambda is unnamed, which implies it will only be used in one place. It can also only contain a single expression, so it should be relatively simple.
its generally bad practice to assign lambda to a var and use it multiple times
Well, it's pointless, for one thing.
You could just declare a regular function then.
and lamda syntax isn't great, functions are much more readable
its good for one offs
There are certain functions that take another function as a parameter, in order to customize its behavior.
If you need to call such a function, but you don't want to declare a proper function for the parameter, you can use a lambda.
sorted(some_list, key=lambda x: int(x.id))
ps: stolen from #esoteric-python
sorted is an example of such a case
It's a function that sorts something, and you can customize its behavior by supplying a function to define what property it should sort by.
anyone uses vscode?
You can declare a proper function to do that, like so: ```py
def my_sort_order(x):
return int(x.id)
sorted(some_list, key=my_sort_order)
im in this weird situation
But that's pretty verbose.
@glad goblet If this is a help question, please see #βο½how-to-get-help
This channel is for discussion, not help.
oh ok
@unkempt rock The version @flat gazelle showed is less cumbersome to write, if you're not planning to reuse my_sort_order elsewhere.
that is pretty much it. You can also give them more parameters for formatting purposes
There are lots of situations where you want to embed values inside strings, and there are a bunch of different ways to do it.
f"{user_name:20}"``` will always be at least 20 characters, padding with spaces. You can make the stuff after `:` more complex to choose a specific char for padding, choose the padding side, limit size of the string, set the precision for float, ...
v1 = "Hello, " + name + ", how are you?" # Cumbersome
v2 = "Hello, %s, how are you?" % name # Better, but hard to know what %s refers to in context
v3 = f"Hello, {name}, how are you?" # Best of both worlds
other things you can use are
f"{str(20)!r}" == "'20'" #use repr instead of str for getting the string to embed
f'{20 + 30 = }' == '20 + 30 = 50'#include the contents within {}, then place the result
| is the or operator, it is set union and bitwise or as well
or is logical/boolean or
| is bitwise or
{1, 2} | {3, 4} == {1, 2, 3, 4}
0b1010 | 0b1100 == 0b1110
{1: 2} | {2: 3} == {1: 2, 2: 3} # 3.9 only
you can customize the behavior with the __or__ method
how does one ensure that the parameters in the docstring reflect those of the function arguments? Is this just visually? Or is there a better / more robust approach
pycharm yells at me if they get out of sync π
it would be nice if sphinx also yelled at you for it
im not sure if theres a standalone docstring linting tool that checks for such a thing. maybe one could be built using sphinx APIs
Hopefully there aren't that many that it becomes impossible to keep track of in the docstring, but I usually only document the ones that need more beyond their name and a typehint
@magic python This is kind of an inherent problem with relying on comments. It's hard to ensure they stay up to date, because unlike code, they aren't validated just by running the code.
I realize docstrings are hard to avoid. I think Pycharm inspections is probably the only tool I'm aware of.
https://docs.pylint.org/en/1.6.0/extensions.html @magic python pylint supports this
can we specify which type of variable do we want in a lambda? is it possible? like in defs
def somemethod(somestr: str, someint: int):
```?
Yes, you can typehint any name
The lambda syntax does not allow annotations, as far as I know
as the : is already in use as the separator between the argument list and the expression
If you assign the lambda to a name, you could probably annotate that name, but then you're assigning a lambda to a name
and not really annotation the lambda object internally
Lambda
lambda's syntax does not support annotations. The syntax of lambda could be changed to support annotations, by requiring parentheses around the parameter list. However it was decided [12] not to make this change because:
- It would be an incompatible change.
- Lambdas are neutered anyway.
- The lambda can always be changed to a function.
https://www.python.org/dev/peps/pep-3107/#lambda
Neutered?
they probably mean that you can do more with a function compared to a lambda
multiple statements etc
They are neutered in the way that they don't carry a lot of debugging information
When you define a function, the function object keeps track of things like the initial name it was assigned to
A lambda does not do things like that
Ah
c = ssock.getpeercert(True)
x509 = M2Crypto.X509.load_cert_der_string(c)
publickey = x509.get_pubkey()
key = Crypto.PublicKey.RSA.importKey(publickey.as_der())
modulus = key.n
public_exponent = key.e``` How to get the modulus of certificate in Python 3?
The above code works for Python 2
@unkempt rock This is not a help channel. If you need help, see #βο½how-to-get-help .
That's not what the topic says.
Discussion on the use cases, implementation and future of the Python programming language including PEPs, advanced language concepts, new releases, the standard library, and the overall design of the language.
No, and don't advertise your help channel in other channels.
Okay
I think we could add lambda annotations
lambda (x = 5: int), (y = 4: str): 5 * (x + y)
but why?
you already know the type the lambda has, because you are passing to something that has a type hint
If you implement your own version of the function type, how do you make functions with it?
A decorator?
sounds reasonable
why would you ever want annotations for a lambda
@hollow crane t y p i n g
but like
you don't type annotate every line of code
a lambda isn't really a function
I think we could add lambda annotations
@rich wharf
It was discussed (parentheses around the entire parameter list), but ultimately rejected
actually, is there a function that works like an identity function for functions?
I'd argue that if lambdas were deliberately used in code, you could probably infer the types from what it's supposed to be modifying/calling back to in the first place
yeah that's my view, it's more like a block of a code than a function
generally, you pass them as args, and that arg has a Callable[...] type
alright
Do you mean like something like:
return comp (f, g)
h = compose(print, id)```?
no, I mean literally
def id(a): return a
``` but in the builtins somehow. Kind of like `int` and `int.conjugate` are identity functions for ints
Looks like there is not
That answer is 8-years old though
probably there is none. Shame
would let you make something entirely with decorators
is c++ return void is the same as python return None ?
or we dont return anything at all is the equivalent?
every function in python returns something, None by default. C++ void means the function does not have a result
so they are not the same thing, but you would return None (or just return) in places where you would use void in C++
just "return" works? wow
you can also do
def fun():
print('a')
print(fun())
``` and get
a
None
printed
@raven pike are you coming from c++?
ah, imagine it more like all objects are pointers (they are in cpython), and None is just nullptr (it's not)
π i'm still not over pointers. i mean not seeing them makes me always think
in cpython everything is Py_Object* π€· (and all functions return Py_Object*, maybe there's some exceptions for special stuff like coroutines)
so you can still pretend you live in a land of pointers
This is a good video to watch when you're coming from a different language: https://www.youtube.com/watch?v=_AEJHKGk9ns
"Speaker: Ned Batchelder
The behavior of names and values in Python can be confusing. Like many parts of Python, it has an underlying simplicity that can be hard to discern, especially if you are used to other programming languages. Here I'll explain how it all works, and pre...
It explains how names and values work in Python really well
doesn't __ things mean don't touch that?
or am i missing something
when looking at the preview
it's python you can touch everything
i'm afraid π
in python __name__ is a dunder
we have no access specifiers
they have a special meaning when used within classes
feel free to touch them
in fact, you must touch them in order to make class fields
if you're coming from c++, i wouldn't worry about lack of pointers so much as lack of destructors
i'm always worried that if my ram would run out π π
when int() takes a minimum of 24 bytes, thoughts of ram kinda fly out the window
a while back another msging app introduced video profiles, and i asked a friend to send me a few looping gifs, and i chose this one π (so no)
doesn't __ things mean don't touch that?
@raven pike
I think there are two things at play here:
- Single and double leading underscores are used to indicate private attributes, with
__attributebeing a stronger indication that also adds some "name mangling" - double leading and trailing underscores ("dunders"), like
__name__are given to names/attributes that have a special meaning in Python/the Python data model
so _name_ are safe?
A lot of those dunders allow you to implement your own classes of objects that behave much like built-ins and that can hook into many parts of the language
You shouldn't create your own; it has a very special meaning
But, you will typically implement the ones that exist
Like __init__ or __len__ or __repr__
__name__ does not mean absolutely never touch this, probably compiler specific like in C/C++.
You probably shouldn't be accessing them directly most of the time because builtins or modules have ways of accessing them. The only real thing you shouldn't do is use their names for your own things or things may break if python does end up using them, and is confusing
in general where in c++ we have operator... or constructors, in python we have __magic__
so like operator+ would be __add__ (i think)
and while (like in c++) you can access them through magic, usually you use the corresponding operator or function
Importantly dunders are not fully polymorphic like c++ operators
c++ operators are polymorphic?
thats function overloading, not polymorphism
Right
You can do operator overloading, but I don't think you can change types
In any case dunder methods on classes only dispatch on the class they're defined on
So + for some type has to return that same type
Interesting
ok i'm confused, king areyou talking about python or c++?
Anyway thats why you have __add__ and __radd__ in Python
When I said polymorphism I meant multiple dispatch
Actually wait, multiple dispatch is for run time?
i think so
__add__ is ladd
oh lol
That's my point, those methods are not symmetric
a + b is a.__add__(b), or b.__radd__(a) if a has no __add__ method
huh ok we actually have multiple dispatch
Finally falling back to built in +
Yeah, this is a hack to implement multiple dispatch on selected binary operators
Yeah. (__add__ may also return the NotImplemented singelton to indicate that it doesn't implement it for this combination of a and b)
Interesting
I always wondered what that was for
https://eli.thegreenplace.net/2016/a-polyglots-guide-to-multiple-dispatch/ anyway time to read up before I get my terminology any more confused
if __add__ returns NotImplemented, does the interpreter than try to run __radd__?
yeah
NotImplemented
This type has a single value. There is a single object with this value. This object is accessed through the built-in name NotImplemented. Numeric methods and rich comparison methods should return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) Its truth value is true. See Implementing the arithmetic operations for more details.
!e
class Foo():
def __init__(self, value):
self.value = value
def __add__(self, other):
return NotImplemented
def __repr__(self):
return f"Foo(value={self.value})"
class Bar():
def __init__(self, value):
self.value = value
def __radd__(self, other):
return self.value + other.value
def __repr__(self):
return f"Bar(value={self.value})"
one = Foo(1)
two = Bar(2)
print(one + two)
@wide shuttle :white_check_mark: Your eval job has completed with return code 0.
3
the only part i don't agree with is it being True why wouldn't it be False
like the name starts with Not
It is the default
You're most probably not going to be using the truthy value of it in any way, so there's no reason to provide a non default value
thats function overloading, not polymorphism
Isn't overloading just ad hoc polymorphism?
(as opposed to parametric polymorphism, which is called polymorphism in OOP)
How would I go about creating polymorphic code and what are some uses?
I think that has some good explanations of when and why you would want to use polymorphic code
@mental totem Do ik you?
yep
we went to school together
franklin
lmao
you where the drone kid
@modern frigate
indeed
I'm trying to think of the most elegant way to define how instances of a certain class are sorted.
but don't you basically have to implement __lt__ and __gt__ for each class?
and __eq__ I believe. Seems to be a way to me.
I believe you only need the lt
I wish there was a __key__ dunder that gets used for sorting if it's defined.
so I could do
def __key__(self):
return (self.a, self.b, self.c)
etc
would also make it easier if you need it to work recursively.
so if self.a isn't a builtin type, it could use __key__ for that class if it's defined, otherwise try __le__.
ok not sure if this is the right place to put this but #python-discussion has been muted so... does anyone know a good place to learn matplotlib? i've found the docs but for python i'm not great at learning from docs cuz i'm not great at python
a good but relatively brief intro into the module that will help me get my feet wet before i dive into the docs would be great
That feels like abstracting a lot, implementing lt isn't horribly inconvenient and makes sense in the context
things like min also use the key arg in a simliar fashion so you'd cause confusion there
theres a @total_order decorator somewhere
functools.total_order
I ended up making a base class for all these classes, and I'll make __key__ an abstract method and make __le__ use whatever that function returns
believe that's total_ordering, but it's unnecessary for sort
you just have to define __lt__ i think with total_ordering, but sort only uses __lt__ anyway i believe
yes
Just feels like complicating stuff more, and making your own dunder also isn't very nice
let me paste the code
!paste
I didn't actually make each class a subclass of the first one yet
I'm very quickly approaching inheritance-as-code-obfuscation territory
Your last class will just error out
it's not done
I don't really see much use for your key as comparing stuff thruogh random types doesn't make much sense. I'm also not sure why you're changing your lists to be tuples when they're both sequences of arbitrary items
dataclasses have a order=True kw
@peak spoke I'm trying to make a framework for interacting with certain text data and I want people to be able to modify it to their liking
getMatche = dimap matchPairs (bestMatch . sortMatches) validMatches
where sortMatches = sortBy (\mA mB -> compare (matchConf mA) (matchConf mB))
validMatches = filter (getPredicate pMatchTest) . map buildMatch
bestMatch m | null m = Nothing
| otherwise = Just (head m)```
vs ```haskell
getMatch = dimap matchPairs bestMatch validMatches
where validMatches = filter (getPredicate pMatchTest) . map buildMatch
bestMatch m | null m = Nothing
| otherwise = Just (maximum m)```
I think the second one looks cleaner and the added quality is worth the few extra lines you need to write
Not sure what I'm supposed to be looking at
π¦
Basically, I think a few extra lines of codes in order to define how to order things is a great abstraction if you plan on sorting in more than one place
I wanted to show you an example but that's the only one I have on hand
(The key thing to note here is in the top one I had make a sort function on the spot or to have a function somewhere that can be called upon. The alternative to this is make ordering a of our class so that we can just use the same sort function we use everywhere else and ignore the little details about what we're sorting over)
thoughts on imports at a lower level (not top of module; in a function/method), after sys.path has been modified? i've seen it in the wild, but it just feels dirty.
i just am in a spot where i need to clone a repo that contains a module i need to use, which may change with the commit ref i'm cloning (this is a CI/testing situation).
Sometimes you need a conditional import- is that such a crime?
I often want to avoid an unnecessary dependency while giving users a choice of - for instance - low-level IO library. So if you donβt pass in your βSPIβ instance, it imports a library and sets up a default.
Actually used this as a crutch to do testing by using a custom IO class that emulated hardware more thoroughly than a mock object could. Have since learned more about mocking.
yeah, i've had plenty of instances of that in smaller interpreters (CircuitPython, which is actually what i'm testing). the constraints there have always been able to override my "its dirty" thoughts. just never personally used it in less-constrained environments. i've seen it a couple places in CPython projects, just not sure how wide-spread it is or how acceptable.
@void sonnet In CPython projects it's usually used as a dirty trick to break circular imports, a la https://stackabuse.com/python-circular-imports/
perhaps also to delay the cost of loading an expensive module until it's actually needed, but in my experience that's rarer than doing it to break a circular dependency.
Does anyone know how to cast a python integer to a C integer? Possibly with cython?
For what use?
i need to send a c int into sdl2 to change the keyboard output for android and ios
0 = UIKeyboardTypeDefault
4 = UIKeyboardTypeNumberPad
ect
This may be better suited to an another channel but should it do that itself? There's always ctypes for something builtin if it's necessary
well the numbers come from python. i could assign them at a lower level in cython
but i thought it should be trivial to cast a python int as a cdef int but maybe its not
it happens implicitly, in fact. if you declare a C function as taking an int in a cdef extern block, then Cython will automatically cast a Python int to a C int when you try to call it. See https://cython.readthedocs.io/en/latest/src/userguide/external_C_code.html#external-c-code
@raven ridge thanks. luckily, i'm not in a circular import. its really just a deferment since i have to wait until i have the "desired" version of the module.
Are async/await considered keywords in Python 3?
Python 3.8?
They were only upgraded to keywords in 3.7, I think
async and await names will be softly deprecated in CPython 3.5 and 3.6. In 3.7 we will transform them to proper keywords. Making async and await proper keywords before 3.7 might make it harder for people to port their code to Python 3.
Yep
damn, soo many keywords
Because if someone had named their variable await or async, making them keywords right away would be a breaking change.
yeah
!e
import keyword
print(keyword.kwlist)
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
As you can see, there are keywords!
It's pretty middle of the road as far as the number of keywords go
This answer on SO has a comparison; I haven't checked it: https://stackoverflow.com/a/4980785
@rich wharf Re: #help-avocado
Here's a hacky implementation that I wrote
https://gist.github.com/PureFunctor/cd1c40d65ee08345cd51cb6aabd662c1
Though if the properties of the decorator are supposed to be passed to the method, that's also different
TypeError: argument 1 must be , not int
tf do i do now
is this a normal error?
ah it's me being dumb and not properly reading documentation
yay it works π
get gud
when debugging one can trigger an ipython session - within this session variables which are in memory can't be used in list comprehensions, does anyone know why that is?
says that it's not found
if you have some list l that you can see with just l <ret>, you won't be able to do [x for x in l if x > 3] or whatever
does l[0], [*l] and such work?
what about vars["l"]
Are python lists arrays?
In the background yes.
They are all the same type, PyObject *
They're arrays of pointers to the python objects, so it's still one type
does this mean that string and integers are all the same type in python?
They are both python objects, but they do have some specific properties as well afaik
I see, thank you
So that means there's no way to store, say, an array of integers side by side in memory? I mean, without calling into some C library?
not that I am aware of, you would need to use something like the builtin array library
import ctypes
ten_int_array = ctypes.c_int * 10
for i in range(len(ten_int_array)):
ten_int_array[i] = i
if array is too boring π
π€
you can also use bytearray for just 1 byte unsigned ints
does python not have atomic types?
like what
it doesn't have fixed size atomic types by default
as in a char or an unsigned long or something
i don't want to use a mutex for a single int :/
for hinting?
no for thread safety
oh wait
yeah
seems like a common problem
maybe python's atomics are threadsafe
idk
or like in assignment
python has atomics?
the only thing i can think of is x = y is atomic, and then if y changes, x won't
(and technically it's only atomic on some platforms)
Joe said this might fit here; Any ideas?
oh yay just been doing this π
I've also tried using a void* as struct member, but that led tho this: cpp src/py_nitro_emulator.cpp: In function βint NitroEmulator_Init(PyObject_NitroEmulator*, PyObject*, PyObject*)β: src/py_nitro_emulator.cpp:8:33: error: expected type-specifier before βnitro_emulatorβ 8 | self->emulator = (void*)new nitro_emulator(); | ^~~~~~~~~~~~~~
it's header only?
it's not; I'm trying to write an extension for a Cpp lib but it uses classes
are you linking the cpp file? (the nitro one)
I am
have you defined tp_alloc, tp_new or tp_init?
# setup.py
import glob
from setuptools import setup, Extension
setup(
name="libnitro_native",
ext_modules=[
Extension('libnitro_native',
sources=(glob.glob("src/*.c") +
glob.glob("src/*.cpp") +
glob.glob("../../src/*.cpp")), # libnitro source; I'll set up linking later
include_dirs=["include/",
"../../include/"], # libnitro headers
language='c++')
]
)
also does python allow c++ classes? even with c++ linkage?
the issue is that nitro_emulator somehow isn't found by the compiler and I have no clue why
is there any other advantages to double assignment over tuple unpacking (for assigning the same value to multiple names)? I know some compilers do this in auto-optimization and that one-less instruction doesn't really matter with modern cpus.
@lost nexus if you provide two samples I can look into what's faster and why
@timid orbit can you try running the command python3 setup.py build executed but with g++ instead of gcc?
I wouldn't know how to make python select g++
one = one_aswell = 1
# load 1
# store one
# store one_aswell
(one, one_aswell) = (1, 1)
# load 1
# load 1
# store one
# store one_aswell
same error with g++
damn :/
In [12]: dis.dis('one = one_aswell = 1')
1 0 LOAD_CONST 0 (1)
2 DUP_TOP
4 STORE_NAME 0 (one)
6 STORE_NAME 1 (one_aswell)
8 LOAD_CONST 1 (None)
10 RETURN_VALUE
In [13]: dis.dis('(one, one_aswell) = (1, 1)')
1 0 LOAD_CONST 0 ((1, 1))
2 UNPACK_SEQUENCE 2
4 STORE_NAME 0 (one)
6 STORE_NAME 1 (one_aswell)
8 LOAD_CONST 1 (None)
10 RETURN_VALUE
``` there is a difference
Well there's no need to use unpacking there where you can just store two names
though do note that
a, b = [], []
``` and ```py
a = b = []
``` are different
i know
DUP_TOP is a lot faster than UNPACK_SEQUENCE
Python is really too high level to worry about cpu instructions (and in most applications lower level languages too)
c++ is fine to worry about asm
@peak spoke i know i'm just curious if there's any other advantages
optimizing bytecode is good as in it speeds things up. But generally at that point you will be better off using FFI
FFI?
foreign function interface, the way to call C stuff
Hey @timid orbit!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg.
Feel free to ask in #community-meta if you think this is a mistake.
ic
:(
Just worry about what's more readable while keeping your behaviour
will dm source @red solar
what do you see as more readable
in the case of immutables the multiple assignment is probably more readable than unpacking, and if you need to do it for something longer it'll be better to just do it on separate lines
yeah
thanks @brave badger
is there a way to synchronize objects in shared memory? do i literally need a lock?
there's no lock free way?
ok ig moving on cuz i can't find anything online
if we had atomic, would it be atomic.long, atomic.Long, or atomic.AtomicLong? (ok probably can't be the first one because with atomic.int, from atomic import * would cause it to clash with int())
thats why you dont from x import *
yeah but you know someone's going to do it lol
thats their own fault IMO
maybe, but i'm not gonna shoot them in the foot for slightly misusing a language feature π
so Long or AtomicLong?
that i have no clue ;-;
damn :/
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
time.sleep(2)
for char in "wwwwww":
keyboard.press(char)
print(char + " was pressed")
time.sleep(0.02)
so basically this code works fine h
however when I enter a game the player doesnt move forward or whatever
how can I fix this? I made sure the code ran
pls help
@unkempt rock please visit #βο½how-to-get-help π
this channel is to talk and discuss about PEPs, implementation of the python language, the future of the python language and etc
you can read more about this on this channel's topic
oh
do you guys think python should borrow series from pandas?
i mean it's like lists but different you know, and it might be so valuable to so many libraries and people ofc
i think not
series isn't just a data structure
it comes with a huge amount of functionality
adding anything to the standard library at this point deserves very very careful consideration
where i can find a list of all global variables that python makes such as __name__?
Probably here https://docs.python.org/3/reference/datamodel.html
Under the "modules" section
This may have it too https://docs.python.org/3/reference/import.html#importsystem
@paper echo not the functionality, the structure. just leave something like _init_ for people to customize it themselves
can arrays be appended?
i meant non-numeric functions, but series like functions should be implemented
an atomic is an object on which operations are indivisible (so thread safe)
@raven pike i just dont see the point
other than "making python itself bigger, harder to re-implement, and harder to test/maintain"
maybe i'm over-thinking
when we already have well-established powerful libraries doing this stuff
if anything we should be deprecating old things in the stdlib like the http parser, xml parser, etc. and handing them off to 3rd parties willing to do their own maintenance. but that's a somewhat extreme opinion
@red solar i think that's the whole point of the GIL, so good luck with that one π
shouldn't there be an initiative first? i mean someone should make something like these parsers; then they can hand it over.
cutting them in order to make community take care of them is sounding like a harsh solution as you put
i think thats backwards
libraries get popular, then they get funding by some big organization like the PSF or NumFocus or Pydata
GIL doesn't help if i want to put my object in shared memory
what language has atomics? c++?
also asked in general but this place seems more appropriate for this one:
how i can retrieve a type stub file? for example for pandas, where can i get it? or everyone doing custom ones for themselves?
id just be curious what an "atomics" library looks like
@paper echo that's kind of scary, orgs behind these; then they might disappear one day?
you don't want to see c/c++'s one - you won't understand a word of it (i don't)
the PSF might disappear too π€·ββοΈ
what parsers?
@paper echo π¦
@raven pike you want to physically obtain the .pyi files? or just make sure that mypy can find them?
actually i'm using pyright; and it can't catch lots of things from docstrings
thought pandas would be written in c - turns out they just use scipy/numpy :/
There's typeshed for python, but you'll have to search for other libraries if they didn't make it themselves
@red solar they have some Cython code at the low level
where? i'm looking at the github
but yes it's based on Numpy (which is mostly C extensions)
there are a few .pyx files in the pandas repo
the official one right?
yeah
or are there some community made ones?
pandas has stub files for sure, idk where they are
i downloaded a mypy extension for pandas, but it's full of false-positives
science-data-types i guess its name
gotcha. do you think chaining might confuse mypy @paper echo
like df.drop(...).dropna(...).etcetc
i've no idea if there's any reasoning to this... but in path lib there's Path().exists() and in pandas there's pd.DataFrame.empty, they seem to do pretty similar things? Why is the pathlib a method and the pandas an attribute π€
exists doesn't seem to take an argument, so idk why it can't just be an attribute too... it probably doesn't matter at all, i was just curious
this is just a guess, but exists is probally calling the system to check it, while empty is just checking values that are in ram. might be wrong on that tho
@magic python
right, makes sense
Is it possible to use a logger across different modules?
I guess I'd have to pass it as an argument to them... not worth it perhaps
within the same application?
You shouldn't have to pass them around
Just use:
log = logging.getLogger(<samenamehere>)
but usually you want unique names that reflect the hierarchy in your project
a common version is
log = logging.getLogger(__name__)
@wide shuttle same application, I guess? I have a script that calls various other modules to process analysis... though maybe that's just bad design from the start π€
i usually pass around loggers, idk why
notably if you run something with -m the __name__ changes to '__main__'
i've been using loguru ... i think this project is probably an unsalvagable clusterfuck at this point though
Passing around loggers sounds like a huge hassle
There's a reason why they are considered to be a valid use case for singletons
@gloomy rain a singleton means that only one instance of it is created?
that only one instance can be created, generally.
@gloomy rain i usually do from mymodule.submodule1 import logger as submodule1_logger
maybe thats bad style
It's an OOP pattern where you design a class in such a way that you can't instantiate it more than once. Not really possible to implement properly in Python, since it doesn't enforce member access control.
so mymodule.submodule1 is the "master" script?
The standard is something like
log = logging.getLogger(__name__)
``` Anything other than that is weird, and makes it harder for users to configure logging for your libraries.
@paper echo i was doing that. gdude convinced me otherwise.
It also essentially makes the one instance a global variable.
yeah i always do that at the top of my module @raven ridge
@void sonnet what was the otherwise π
i just dont typically use getlogger when i need to get another module's logger, i just import it from that module
(at least within an application)
I have
from loguru import logger as log
π€
you should never get another module's logger - I'm curious how you got into a situation where you wanted to do that in the first place π
@raven ridge in __main__.py when i'm configuring output to the console
like if i run with a --debug option
Not unusual in testing
that too ^ to make assertions about log output
