#internals-and-peps
1 messages · Page 76 of 1
How terrible of an idea is it to have parallel modules with the same name?
What do you mean by "parallel"
So like I have:
-pkg
-subpkg
-moda
-subpkg2
-moda
Also if your top level package has an __init__.py do those subpackages then also need them or can you rely on implicit namespaces? I ask because I seem to be getting ModuleNotFoundError: No module named <module> for modules in folders without an __init__.py despite being on 3.8
Hello
Is it possible to run some processes on the GPU rather than CPU?
@safe hedge having two submodules with the same name at the same depth under different packages is fine. No one will get confused between
chef.appetizer.recipes and chef.entree.recipes, and as long as the names don't confuse readers I'd say you're fine.
As for the other question, what you're making is a regular package, not a namespace package. You need an __init__.py
Ok thanks. Basically I have a “functionality/core” package and then a “commands” package with submodules reflected
As for the other question, what you’re making is a regular package, not a namespace package. You need an
__init__.py
@raven ridge so yeah namespace packaging is all or nothing?
Yes. It has to be, just by the very nature of what namespace packages are.
You can't put a namespace package inside a regular package, because namespace packages don't have just one location on disk, and regular package do.
If you could put a namespace package inside a regular package, you would no longer be able to use it as a namespace package
PEP 420 made it so that if you were going to make an __init__.py that just contains
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
``` you no longer need to create that file at all.
If you weren't going to put that into your __init__.py, then PEP 420 didn't affect you. If your __init__.py would have been empty in a pre PEP 420 world, you still need an empty one in a post PEP 420 world.
420
Implicit namespace packages make it easier to do the wrong thing than the right thing, unfortunately. Namespace packages are an advanced feature of the language designed for allowing a single Python package to be composed of many individual PyPI packages installed into different directories. This isn't a thing average developers need to do. But now that it's harder to create a regular package than a namespace package (creating an empty __init__.py versus not creating an __init__.py at all), regular developers are creating the wrong type of package all the time.
Yeah I didn't really want a namespace package I thought maybe I just could take advantage of it in some of my nested subpackages which would have empty inits
If anyone is good with datetime module come to #help-broccoli
@unkempt rock This is not a help channel, read the channel description. Don't advertise your help channel anywhere, please. If someone wants to help, they will help.
@safe hedge I think it's fine to have empty init files
@raven ridge I wish they would have just created a new dunder file instead
Or some other explicit way to declare that a package is a namespace package, but without manually hacking around with the path
__init_namespace__.py
Idk
I get that the problem is, you need to prevent users from putting actual python code in that file
Heck, just call it __init_namespace__ and require that it be empty (or ignore its contents) - like py.typed
Or call it py.namespace analogously to py.typed
Or some other explicit way to declare that a package is a namespace package, but without manually hacking around with the path
@paper echo The problem with the old status quo was that some PyPI package needed to create the__init__.py, which meant that in practice when multiple packages all wanted to install into the same namespace, all of them would create an identical__init__.py, but then some packages are overwriting files created by other packages, and if you package those PyPI packages up as Debian .deb packages or RedHat or Arch packages or whatever, the__init__.pythat made the namespace package would conflict across all of those packages.
in other words, any solution that involves creating a new file wouldn't have solved the problem.
Yeah i get the need for namespace packages & the desire to make them implicit
I imagine that a tool like setuptools could reconcile all that stuff
So the deb version would in fact have an empty file
Then again having a file whose existence is a sufficient check also solves the problem, no?
no, it doesn't. because if two different .deb packages both contain site-packages/myns/__init_namespace__, then Debian won't let you install both of those packages, because they conflict with each other: both want to own the same file.
yes.
in practice the solution to this was making a package that provides only site-packages/myns/__init__.py and doing the extend_path magic in there, and making every myns-foo and myns-bar package declare a dependency on the myns package, which needs to be independently published.
which worked, but was terribly inelegant, so implicit namespace packages are a solution for the problem that doesn't require creating artificial packages just to make an explicit namespace that other packages can depend on.
Do I have to setup a special configuration to read all lines from asyncio.subprocess (create_subprocess_exec)
because as soon as i try to read all lines from process.stdout.readline() with a while True
I end up in an infinite loop
For no reason... I guess
finding someone to help out with this topic is quite hard, im now trying to use a third-party lib that makes the same, anyio
@sacred yew but this is the code I was having problems with https://dpaste.org/odK1
if you're able to figure out whats wrong i can try again
would it really be bad if frozensets were created with f{}?
well, {} is not a set, to begin with
like f{1, 2, 3}
I know {} isn't a set
empty frozensets can still be created with frozenset()
My take is that frozenset isn't a common enough type to warrant new syntax just for it
Because code is meant to be read, not written.
And reading it is already harder than writing it. So there's a cost to adding new syntax
Also, when you hit a function you don't know in some code that you're reading, you can Google it. That's much harder to do with syntax.
Why not frozendict
Why not
frozendict
@swift imp rejected a while ago
there was once or twice I actually needed it (mappingproxy is not a perfect substitute)
Hello everyone, I’m sorry if this isn’t the correct channel to post in, but I’m an intermediate python programmer, and I’m stuck for project ideas. Can anyone help?
it is not the channel, but there is a link for project ideas, ask in #community-meta for that link.
Thanks!
Can someone help me out for an app development for my university project?
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
We will not help with graded assessment
hey guys i am trying to make a software -in python- that when you double click on desktop it opens the FILE EXOLORER, any one have an idea about how to do this??
hey guys i am trying to make a software -in python- that when you double click on desktop it opens the FILE EXOLORER, any one have an idea about how to do this??
@blissful hornet subprocess.Popen('explorer "C:\path\of\folder"')
Like that?
yep
but am asking about how to double click on the desktop to open the explorer
i looked a lot for that
So you're asking how to detect double clicks?
yeah, on DESKTOPS ONLY
okay, sorry, someonelse might answer that
k this it the problem
This is not a help channel @ancient lintel
See #❓|how-to-get-help if you need help
oh my bad
@tropic gale i dont think u can compile python to an exe for example
because some features wouldnt work if it was not intrepreted
like eval() or exec()
maybe try https://pypi.org/project/auto-py-to-exe/ ?
np
just be careful some stuff wont work @tropic gale
pure python without import might be fine? i havent tried it myself
It needs imports to run. But I'll see what I can do though.
maybe try this @tropic gale
Anyhow, not really on-topic for this channel. I could suggest getting a help channel though.
@wintry radish okay. 👍🏿
Hello. So the scenario is that I’m trying to link a python script as backend to a front end. How do I make a front end with very decent UI. Like what language and how do I link it with python
Sorry if it’s not advanced
Please don’t suggest tkinter please no don’t
@rare ocean there are many options but the simplest will be that you wrap your script in API and create a front end for it.
You can use flask(simpler) for it or django (more complex).
There are also some simpler alternatives if you don't have much experience with flask or django like framework. Like streamlit.
You can check it out and is nice if your script is for personal use or just for some presentation purpose.
Or you could use a non-web UI that's not tkinter, such as PyQT
Not sure if I am asking in the right channel. But, I want to use a namedtuple to cleanly combine a bunch of filter parameters passing into and then used inside a class. Example of the parameters:
minEfficiency = 1.25
minPercentile = 3
maxPercentile = 50
minDays = 3
maxDays = 5000
minStrike = 0.25
maxStrike = 3
I like namedtuples because they are immutable and their indexing is succinct compared to dicts. For example, I much prefer filter.minDays over filter['minDays']
However, I am struggling with how to overcome two things in my implementation.
- I will be assigning the namedtuple outside of a class and then passing it in as a parameter, but then using it a bunch inside of that class. I feel like the namedtuple's structure should be defined inside of the class. What is the best way to do that?
- Related to #1. Is there a way for the class to define the structure of the named tuple w/o necessitating the use of
selfeverytime I want to access my tuple data inside of the class, for example, Badself.filter.minDays, goodfilter.minDays?
Re 1: Why do you think the namedtuple should be defined inside the class? Re 2: Not really.
I am thinking what I want to to create a simple class that inherits NamedTuple... I think that gives me what I want... never done that before.
Yes, that's quite a common pattern. You can inherit from a specific namedtuple even; class MyTuple(namedtuple("Foo", ["x", "y"])): ...
Re 1: Why do you think the namedtuple should be defined inside the class? Re 2: Not really.
I know I said it should be defined inside of the class, but I guess it doesn't have to be. It could be defined outside of the class but in the same package.
Yes, that seems more reasonable. Think of a namedtuple like a class.
So, then, I don't get this...
class MyTuple(namedtuple("Foo", ["x", "y"])):
# what goes here? Is it just empty?
Not being a CS guy... I am having a Inception level confusion about how this inheritance works.
The namedtuple function creates a class object for you, very much like type
Although I think typing.NamedTuple is better suited for that purpose
I think you are right @brave badger, as you typed that response, I was reading this...
http://zecong.hu/2019/08/10/inheritance-for-namedtuples/
tl;dr: Inheritance for the Python built-in namedtuple does not work as we expect. This blog post demonstrates how to create a custom namedtuple class that su...
which provided this example, which seems perfect...
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int = 0
p = Point(1)
print(p.x, p.y) # 1 0
The relationship between collections, collections.abc and typing always perplexes me
What is the point of naming a named tuple? To clarify...
Foo = namedtuple("Foo", ["x", "y"])
The second "Foo" seems redundant.
It's a class factory, and the class it creates needs to have a name
It's useful in in the string representations for example
It's useful in in the string representations for example
@peak spoke
Do you have a link I could read that shows an example of where this is useful? Or something you would suggest I read.
I’d rather use attrs/dataclasses instead of namedtuples
i was wondering about obvious attrs usage the other day -if you had several functions with similar parameters which had similar meanings, would you use an object for those instead?
def f(x, y, z):
....
def g(x, y, z, t):
...
replaced with
def f(location):
...
def g(location, time):
...
I’d rather use attrs/dataclasses instead of namedtuples
@cloud crypt
I'll have to check that out, if you have a link I can check out to read about them, please share.
https://docs.python.org/3/library/dataclasses.html — standard library since python 3.7
https://www.attrs.org/en/stable — pretty much what inspired data classes in the first place
Reading about dataclasses, it seems like I should use them instead of from typing import NamedTuple if I want mutable data.
@cloud crypt is that a valid conclusion on my part?
And, thankyou for the links
it depends, really, but for classes based on manipulation with attributes, I think yeah, that’s a way to go
Does anyone know beautiful soup?
@manic hatch this not a help channel - and just ask a direct question rather than asking around the question #❓|how-to-get-help
#help-pineapple is the help channel
It's a class factory, and the class it creates needs to have a name
@peak spoke
Aha!!! I get it now. I have to name the tuple simply because (as you said) namedtuple is a class factory and is actually creating a class behind the scenes. So, Foo is the name of the instance and "Foo" is the name of the class. I guess, the authors of namedtuple could have made the name optional and given it a a GUID name or something guaranteed to be unique, but they didn't, or let you pass in Foo as a parameter and assigned it inline. But, that would have taken the understandable concept of a class factory and made things even more confusing.
I guess that is one of the reasons they created the typing library.
I am perplexed by why there are so many different ways to do these types of things...
typing.namedtuples, collections.namedtuples, dataclass...
And then dataclass uses decorators, collections.namedtuples uses a class factory, and typing.namedtuples doesn't use decorators but feels very similar to dataclass.
Seems like dataclass and typing.namedtuples should be more similar in how they are used in practice.
the NamedTuple from typing is just an another (nicer) way to construct a collections.namedtuple. Dataclasses offer a lot more compared to the namedtuples by not being a tuple at the base (mutable, field names matter etc.) the pep for dataclasses is quite extensive https://www.python.org/dev/peps/pep-0557/ and may be worth a read
I can tell you right now dataclasses >> namedtuples and NamedTuple. dataclasses are soo freaking nice. Reduces so much boiler plate while simulatenously being really dynamic. You can do class factories with dataclasses.make_dataclass too. You can even make them hashable by doing frozen=True, eq=True in constructor
Sometimes you just need named fields, and namedtuples are perfect for that
namedtuples are exactly that, just fancier tuples, while a dataclass is a boilerplate class
So you'd use namedtuples when you'd do fine with a tuple, but attribute access would be nice
true, but you can effectively make a namedtuple with a dataclass by doing dataclass(eq=True,frozen=True) and you get the added benefit of being able to add extra metadata and stuff
I mean I guess if you arent doing anything extra, just use a namedtuple but imo being able to add slightly extra metadata is worth it
namedtuples still have things like index access and iteration, and IIRC their overhead is less significant than that of a dataclass, so, again - if all you need is a tuple, but with added attribute access, namedtuple would be the right tool for the job
True
but for example anyway, no iter, but thats ez
from dataclasses import dataclass, fields, make_dataclass
dc_namedtuple = make_dataclass("dc_namedtuple",[('x',int),('y',int),('z',int)],namespace={'get_fields': lambda self: fields(self), '__getitem__': lambda self, item: getattr(self, self.get_fields()[item].name)})
ex = dc_namedtuple(1,2,3)
ex[0]
ex.x
They're actual tuples and interchangeable with them, so you can pass them around to modules expecting tuples, in the (improbable) case that it matter them not being direct python objects helps with the overhead etc. Right tool for the job and all that
Thats a good point, thats what they were used for originaly right? interfacing? namedtuples that is
Their main purpose is to bring the named fields to be self documenting instead of the indices which mean nothing without additional information
here's an interesting piece typing.NamedTuple is actually a dataclass https://medium.com/@jacktator/dataclass-vs-namedtuple-vs-object-for-performance-optimization-in-python-691e234253b9#:~:text=NamedTuple is also DataClass%2C but,faster at only creating object.
Thanks for all of the discussion, this has been very enlightening for me!
Does anybody use task/project man. tools?
The attr access though namedtuples has to be delegated to tuple's getitem so it can't be faster there
What if I wanted to be able to have nested attributes, is that something that is easy to pull off? For example something like this (had to make up some of the syntax because it is not apparent to me the right way to do this)...
from typing import NamedTuple
from dataclasses import dataclass
from collections import namedtuple
# Something like this
class MyTuple(NamedTuple):
x: int = 2
y: namedtuple('nestedtuple', 'a b c') = (5, 6, 7)
# Or something like this
@dataClass
class MyDataclass():
x: int = 2
y: namedtuple('nestedtuple', 'a b c') = (5, 6, 7)
myTuple = MyTuple()
myDataClass = MyDataClass()
print(myTuple.y.b) # 6
print(myDataClass.y.c) # 7
I only used namedtuple inside MyDataClass(): to get the idea across, I don't actually want it to be a tuple in that case.
Not sure if dataclasses have anything nicer as I haven't worked with them extensively, but you can simply create two namedtuples and then assign them inside each other etc.
That makes sense. I guess the same would probably be true for dataclasses... Although, not having to define the nested class as a separate class would be nicer, or rather, doing it inline would be nicer and more succinct.
#help-popcorn Its pretty advanced, just had to share pictures with explanation to make a understanding, aka reason why I am linking the help room here
The size stats from the article also don't seem right to me, tuples don't have to use dicts etc. so I assume it's because they used getsizeof which includes the fields for tuples but only counts the actual object with python classes (that don't define it)
Just playing around with nested NamedTuples, doing something wrong:
from typing import NamedTuple
class Fees(NamedTuple):
flat: float = 0.0
percent: float = 0.1
contract: float = 0.2
class Filters(NamedTuple):
minStrike: float = 0.25
maxStrike: float = 3
fees: Fees() = (1.0,2.0,3.0)
filters = Filters()
print(filters.fees.flat)
Output:
Traceback (most recent call last):
File "c:/Users/HomeLaptop/Documents/FarmTrader/test.py", line 9, in <module>
class Filters(NamedTuple):
File "C:\Users\HomeLaptop\AppData\Local\Programs\Python\Python38\lib\typing.py", line 1616, in __new__
nm_tpl = _make_nmtuple(typename, types.items())
File "C:\Users\HomeLaptop\AppData\Local\Programs\Python\Python38\lib\typing.py", line 1590, in _make_nmtuple
types = [(n, _type_check(t, msg)) for n, t in types]
File "C:\Users\HomeLaptop\AppData\Local\Programs\Python\Python38\lib\typing.py", line 1590, in <listcomp>
types = [(n, _type_check(t, msg)) for n, t in types]
File "C:\Users\HomeLaptop\AppData\Local\Programs\Python\Python38\lib\typing.py", line 149, in _type_check
raise TypeError(f"{msg} Got {arg!r:.100}.")
TypeError: NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type Got Fees(flat=0.0, percent=0.1, contract=0.2).
can someone guide me to where there are discussions that are you know very low level
You need to use the class itself for the typehint, and then construct an instance for the value
You need to use the class itself for the typehint, and then construct an instance for the value
@peak spoke
I can guess what you mean, but not with any accuracy. What would this line look like?
fees: Fees() = (1.0,2.0,3.0)
fees: Fees = Fees(...), the typhint needs to be to the type of the value you expect, not an instance
can someone guide me to where there are discussions that are you know very low level
?
maybe a helper?
@peak spoke that did the trick, thanks!
@nova meteor If you want to get help with something, use a help channel. See #❓|how-to-get-help
Hey y’all. So I was kinda just wondering if anyone out there has used Swift with python?
I’ve really been wanting to dive back into Swift, Swift UI but the reason I dropped it was because it just wasn’t practical for me. It served no purposes. Python however did at the time. But now I want to like intertwine the two. Maybe use python as a backend and use SwiftUI as a front end.
But yeah, just wondering if anyone has ever used python and swift together
i need a python module for console stuff, such as cleaning the console without buffering and mouse input relative to the console
Not the right channel, but curses should at least be similar to what you're looking for @stuck barn
whats the right channel then?
#python-discussion or #user-interfaces probably, this channel serves a completely different purpose
@stuck barn Check out #❓|how-to-get-help
Anyone familiar with scrapy ?
Never used it but have done plenty of scraping with requests, beautifulsoup, and selenium.
@stoic sandal Just read your thing in #general. Honestly, Selenium would be way easier.
@coarse basalt I used selenium before but I think scrapy is much faster
Even dead turtle would be faster than selenium, use js scrapers for speed, python ones for flexibility
Anyone have any thoughts about Dataclasses vs Named Tuples? It looks like named tuples are a little faster to create but dataclasses have faster read times.
i think it would be a very rare application that would choose based on speed.
Dataclasses are supposed to be about 10% faster if my memory is not corrupted, but anyways it is very marginal difference in such slow language as python is
i'm not sure why people are so drawn to micro-optimizations
If there’s a choice between two things, where one performs better and they both complete your task, why not choose that one?
Obviously, it’s best to choose the best suited one, but if we assume that the alternatives work in close to the same ways
Well, micro-optimizations in my case might be making a difference, I am performing some pretty computationally expensive algorithms. My thoughts so far are that Data Classes might look a little nicer in the autodocs and be slightly faster, while I'm already using namedtuples in the project and am more used to them. Wanted to see if there were other considerations I might be missing between the two
Although, now that I think about it, I'm performing all of those algorithms outside of the data structure, lol.
Most of them, anyway
@spark parcel theere didn't seem to be any comparison of behavior, only speed.
My mention about speed was just referring to my limited knowledge of the subject.
I am performing some pretty computationally expensive algorithms.
if you're interested in the best optimization with Python & computationally expensive algorithms then something like Cython may interest you
It's something on my plate to learn 🙂 Right now I'm just leaning heavily on numpy/scipy
Yeah. I assumed that the behavior would be the same or very similar, since they were compared
In terms of accessing the data, it's extremely similar. The difference is that with a dataclass you're actually creating a class to store the data while you're just creating an object of type/class namedtuple for the other.
It looks a little different in documentation and behaves slightly differently with autodoc generators
I think what namedtuples have over dataclasses is that they are indexable
i'm not sure why people are so drawn to micro-optimizations
@spark magnet in general?
yes
I'd say it's because a) humans are very bad at identifying bottlenecks
Well, there's a difference between micro-optimization and making the best design decisions.
and b) very bad at understanding just how fast computers are nowadays
The choice of data structure is a design decision
That may have implications down the road of your project
for you*
(entirely unrelated to your specific case @pseudo cradle)
for your*
just making a general statement
sure, which needs to consider behaviors
with regard to namedtuple...
I mean, I think people often overoptimize as well.
often
a drawback of namedtuples: they are considered equal if they have the same elements, regardless of their types
I mean, I've said this many times before; some form of name-destructurable container would be really nice
and also that
they are also accidentally iterable.
example:
class Point(NamedTuple):
x: float
y: float
pt = Point(1.5, -2.0)
# which is right? you can't tell without looking up the definition
x, y = pt
y, x = pt
It has been proven that the most of 'too slow' applications has some flaws on the algorithm level, like let say traveling salesman problem, u can't optimize code good enough to handle the mathematical problems so i was never into micro-optimizations
a downside to dataclass: you can't do x, y = pt
I mean sure, you reduce time complexity before you optimize the code beyond that
compared to:
scala> case class Point(x: Int, y: Int)
defined class Point
scala> val pt = Point(1, 2)
pt: Point = Point(1,2)
scala> val Point(x, y) = pt
x: Int = 1
y: Int = 2
Ah, you can't unpack dataclasses like you can namedtuples?
You could do pt = Point(x=1.5, y=-2.0) though, right?
@pseudo cradle perhaps I was not clear
Ah, you can't unpack dataclasses like you can namedtuples?
@pseudo cradle nope
the point is not how a Point object is initialised
but how it is destructured
Gotcha
you can use x, y = dataclasses.as_tuple(pt)
you need to visit the definition to know the order of fields
or something like that
True
and there's no simple syntax for destructuring
on the other hand, functional languages can usually pattern match on this kind of abstraction
like the Scala example above
nice
I do need to get more comfortable with dataclasses at some point, but I think for my current project/purpose that namedtuples are better suited. Thank you for the conversation, it was enlightening.
rather than the performance differences, I'd be more concerned with the maintainability differences. The fact that namedtuples are iterable and unpackable means that they can't be extended - the fields they contain, and the order that those fields occur in, is now part of your public interface. Reordering fields or adding new ones can break your users.
and actually, another point: with knowledge and experience comes an ability to understand what optimisations should be made right off the bat.
for example, if you only need to do membership testing with a collection, and that collection will be big, it would be an obvious design decision to use a set.
Damn gg, right when I had made up my mind, haha
but if you never learnt about the differences, you would probably micro-optimise something totally unrelated
if it's a private type used only within your own module, that's nothing to sweat - you have all the flexibility you want to change the type however you want. If it's something public you're exposing to users of a library, though, dataclasses are safer.;
In the short term, some users may be exposed to this. In the long term, it's just going to be done through API calls.
It probably needs to either be easily expandable or trivially expandable by myself. It's a tool/library in high demand right now (internally).
So I guess that's something I need to consider, how easy it would be for me to personally maintain/expand
It's true that any use of its iterative capability I'd have to be careful of
the entire reason we're using Python is because we care more about maintainability and speed of development than speed of execution. There's definitely some amount of coders needing to use their best judgment, but if there's ever a tension between maintainability and performance, it's probably better to err on the side of maintainability.
Dataclasses would force me to resist the urge to iterate through it, lol
yep.
I might need that. It's just so tempting, lol.
While you're hear, gg, do you have any thoughts about Jupyter Notebooks?
here*
Nothing informed. I've barely used it.
Gotcha. People either seem to love it or hate it.
I've started using IPython a little bit, but I've hardly done anything with Jupyter.
I don't like the idea of something that shoves me out of the terminal and into the browser, though I get that it's lower friction for others.
I've found it useful for presentations and executives seem to love them
But it has downsides
no linter, hidden states, etc.
I don't like the idea of something that shoves me out of the terminal and into the browser, though I get that it's lower friction for others.
@raven ridge it's really good for data scientists because of the visual aspect IMO
Yeah, I'll be working closely with a data scientist in the future, so I need to up my familiarity with it
Also my boss LOVES them for some reason. Like, he literally bugged me every day until I set one up
@gleaming rover yeah - I've seen some cool stuff done with it that blends in HTML, too. It's not a need that I tend to have, so learning Jupyter, and getting used to using the browser as a REPL, isn't appealing to me.
You don't ever have to give presentations?
but it's not a "love it or hate it" thing for me. I'm pretty indifferent to it.
it depends on the kind of presentation that you have to give.
Presentations of data? No.
My presentations are either no slides, screenful of code, and explaining what it does and taking questions, or a powerpoint deck.
it's a great thing to have, but it's not a Swiss knife
I heavily used draw.io and now jupyter notebooks for my presentations
Oh, I have to present things to people who will just look at me blankly if I show them a screenful of code
yeah, which is why it depends on the kind of presentation.
if your primary audience is nontechnical and you're showing stuff like data visualisation, then Jupyter tends to be a lot more helpful
If someone is tech savvy I'll just give them the help docs and tell them to hit me up if they have any questions
I found it quite useful back when I was taking notes for CS lectures and stuff. Having pandoc-flavoured markdown lets you integrate latex expressions in your markdown cells, which was quite handy.
I found it quite useful back when I was taking notes for CS lectures and stuff. Having pandoc-flavoured markdown lets you integrate latex expressions in your markdown cells, which was quite handy.
@peak pollen oh yes I loved this
Oh, I bet they'd be pretty nice for CS classes
yeah I taught a DS bootcamp and Jupyter notebooks were basically the only place Python code was run
Nice
(which I don't really agree with as a teaching method, but it was helpful)
aha nice
like there was this perception that Jupyter notebooks were the way to run code and "scripts" (meaning modules) were like an alternative for edge cases
but well. mass-market education.
thank you 🙂
I've found Jupyter notebooks helpful, but pretty awful for actually developing the code
I've found Jupyter notebooks helpful, but pretty awful for actually developing the code
@pseudo cradle yup, precisely
I mean, I use them to poke around with code sometimes
the fact that you have cells is nice for experimenting real quick
then after a while I move to PyCharm
once I have an idea of what I want to write and what it should look like
It is pretty cool that you can just rerun cells without having to rerun the program if you get an error
yeah, that's a great function
yep, pretty much the only thing I use it for these days is messing about with APIs and/or visualising data
like there was this perception that Jupyter notebooks were the way to run code and "scripts" (meaning modules) were like an alternative for edge cases
@gleaming rover I've taught classes that used repl.it and had pretty similar experiences - the advantage of having something that students can try out right in the browser is that it's really low friction to get started, but it does lead to confusion about how programs are actually written in the real world.
does _init_ returns None or the class object?
there's a great talk called "i don't like notebooks" if it hasn't been mentioned yet
https://www.youtube.com/watch?v=7jiPeIFXb6U on the caveats of notebooks
I have been using and teaching Python for many years. I wrote a best-selling book about learning data science. And here’s my confession: I don’t like notebooks. (There are dozens of us!) I’ll explain why I find notebooks difficult, show how they frustrate my preferred pedagogy...
@unkempt rock __init__ returns None, __new__ returns an instance of the class.
oh interesting, I'll check it out
funnily enough, it was presented at jupytercon 2018
then when a new class instance is created, the _new_ method is called and it tries to call _init_?
when you call f = foo(), the interpreter calls f = foo.__new__() to create a new instance, and then calls f.__init__() on the instance to initialize it.
then when a new class instance is created, the _new_ method is called and it tries to call _init_?
@unkempt rock use `code_here` to format your code
__ will underline stuff
Yeah, I've watched presentation
yep, i messed the backslashs
It's really good and did cover a lot of the stuff I was running into as a Notebooks beginner
when you call
f = foo(), the interpreter callsf = foo.__new__()to create a new instance, and then callsf.__init__()on the instance to initialize it.
@raven ridge also thanks for the explanation :D
also, __init__ is not called if __new__ does not return an instance of the class
Being able to quickly run strings of code I feel is kind of offset by the lack of a linter. Like, I think you can get one in there but it's a massive pita
e.g.:
class X:
def __new__(cls, *args, **kwargs):
return 0
def __init__(self):
raise RuntimeError
X() # returns 0, doesn't raise RuntimeError
I'd rather have my text editor let me send code to the interpreter directly
because it wouldn't make sense to run __init__ on an instance of another class
that way I have linting, autocompletion etc
!pep 634
cool
Well, actually seems like 3 new peps were made
The spec, rationale, and tutorial are separate
Which makes me suspect that this might actually be added
I just assumed it was gonna
btw, I was wondering, what exactly is meant with https://www.python.org/dev/peps/pep-0622/#don-t-do-this-use-existing-method-dispatching-mechanisms
Like, how can oop replace this sort of matching?
It's essentially the difference between matching between structures and types
e.g. why dispatch based on the "shape" of sometuing if you can simply dispatch on the types?
So like, by calling isinstance?
and/or using methods
soooo like.... using polymorphism and sorta replacing the matching with a single call to a method?
I'm trying to login into a website using request, i post the information but it seems that it just loads the login page again without any errors
can someone help me please
@stoic sandal This is not a help channel. See #❓|how-to-get-help
Soooo, wouldn't it be nice if python had support for arbitrary base numeric literals?
and like, there's built in int(string, base), but not the inverse, just hex(), oct() and bin()
the asymmetry does seem odd
heroku cant import exceptions from asyncio #help-chestnut
@grave jolt can you help me?
@swift imp It means it has been replaced by a newer PEP, https://www.python.org/dev/peps/pep-0001/ has some information on how PEPs are strutured
see 634, 635 and 636
Google isn't finding them
So it's confusing
I found them, man it's crazy they need to break it into 3 peps it's do big
can anyone give a look at #help-cake
The peps that supersede something usually have their assigned numbers around the original one, so the index should help there
@unkempt rock Don't ping random people. I just said in my last message that this is not a help channel. See #❓|how-to-get-help
Guys is there a float command in pseudocode?
you can make whatever command you want in pseudocode
note that this channel is meant for discussion, you should check out #❓|how-to-get-help for future questions @vocal bluff
does anyone know of a good resource for explaining why there is pyproject.toml and setup.cfg, why I would use one over the other, and what the defined purpose of each is... I have projects which use both, but I just follow what was already there, I use flake in setup and pylint in toml, absolutely no idea why
pyproject.toml is the result of a desire for a better system for specifying build dependencies. There are two PEPs, PEP517 and PEP518, which together explain why pyproject.toml became a thing. Other tools started using pyproject.toml as a configuration file by allowing users to add settings to it. This was initially "forbidden" by PEP518, but that was changed after the authors realized that is was happening anyway and it probably wasn't a bad idea.
Since then, more and more tools allow you to add configurations to pyproject.toml instead of, say, a tox.ini or other config file
We're now in a situation where some tools support pyproject.toml, some tools support setup.cfg, some tools support tox.ini, and some tools support custom config files as well (such as .flake8).
This is a slightly dated write-up on the subject: https://blog.pilosus.org/posts/2019/12/26/python-third-party-tools-configuration/
Slightly dated in that some tools may have added pyproject.toml support since, I haven't checked
What you should use is up to you, although I'm hoping to see something like the pep517 build tool to come out of its "experimental" phase and into real use. My guess is that more and more tools will start supporting pyproject.toml, which means that you may end up with fewer config files in the future
there's any way to get an object from the superclass of an instance without inner class calls?
You should be able to access it directly using b.b, as class a will be part of the MRO of class b
!e
class A:
attribute = 10
class B(A):
pass
b = B()
print(b.attribute)
@wide shuttle :white_check_mark: Your eval job has completed with return code 0.
10
@wide shuttle thanks a lot for the context and links 🙂
Does anyone else find themselves using python more and more like a typed language?
With type annotations, mypy, heavy reliance on typed libraries like numpy, etc
Even dataclasses rely on fields being typed
numpy doesn't have type stubs yet
yes, I annotate all my code, but I don't use mypy much
usually without the annotation you have some kind of type documentation in the docstring, to me the annotations are a more effective way of doing that can also be used by tools such as mypy or your IDE
I'm using annotations in most of my code, and I'm using pyright in real-time (in VSCode)
It feels like I'm going against one of the fundamental tenets of the language by only living in the typed areas
it's part of the language's syntax, you're using a native feature
I'm using a native feature, but one that feels like a concession as opposed to a primary component
i mean at this point, the benefits of dynamic typing are close to non-existent, it's just now up to the language to provide us with the tools we need to express statically typed programs without it being ugly and verbose
I never was a fan of the dynamic typing. I'm sure there are uses for it, but I can't think of any
Well, you can still have not-fully-typed (like Dict[str, Any]) things, and you can have untyped areas/modules.
If your code is fully annotated and has no magic/unspecified relations, then the code probably could've been rewritten in a statically typed language.
I guess that's useful, but it seems like a union would do just as well, unless you truly needed it to be anything
as opposed to just some selection of types
The dynamic part makes it easy for others to pop in their own behavior and testing that's easily implemented
Any in general is either you doing something weird or you being lazy
Maybe it's just not useful in the stuff I do. I deal with complex algorithms and there's never a time I want something untyped
or the type system being too limited, which happens way to often with the current state of python
Yeah, but then, that's a more fundamental question. Whether or not typing should be more supported in Python
i like the idea of adding gradual typing in existing dynamic languages, but one issue here is that the core maintainers are strictly against using them for optimization or doing any kind of static analysis directly in the interpreter
so it doesn't encourage people to use them
Brief aside, does anyone have any opinions on creating a dataclass vs importing the make dataclass method?
huh?
i'm not sure i understand
make_dataclass is an alternative way of creating dataclasses, it's meant to be used instead of defining a new class, i'm not sure what you mean by "importing" here
Sorry
What I meant was, defining a dataclass versus using make_dataclass
Could have been more clear on that
by default, use a proper class definition
Well, make_dataclass won't play nicely with static analysis tools, right?
like namedtuple vs NamedTuple
Right, it's similar to namedtuple's method
It's probably better to use a class definition if you're not creating the dataclass algorithmically
Yes
dynamic creation of types is ugly
I haven't used that in non-esoteric code, I think
I had a piece of code that created a metaclass and a metametaclass dynamically
@pseudo cradle Some people recommend Julia as a statically typed alternative for data scientists, but I haven't tried it. It surprised me with some cool concepts a while ago, but I don't remember what exactly. Maybe you could try it.
Maybe I'll check it out
I've definitely heard the name being tossed around enough
same with Rust
It probably doesn't have the same amount of libraries, though.
Yeah
I'm not a fan of Python's dynamic typing, but I am a fan of the ecosystem and the sheer amount of open source libraries with permissive licensing
julia isn't statically typed
i have some tiny hope in nim in that regard, but i doubt python is going anywhere
it'll probably stay the industry standard for at least a few decades
julia doesnt interest me, its supposed to be a simulink/matlab replacement but its just meh
I get it, its free but like why would want to write C/C++ code for Julia when I can just use Simulink and it generate C/C++/HDL code for me.
I am not following
one benefit of julia is that you get decent performance without having to wrap C++ code
that's one of the main selling point of flux.jl, it's written in pure julia, making it easier for people to contribute
unlike python libraries
julia isn't statically typed
really?
If you want to SIL/PIL/HIL testing you have to write your own C/C++/HDL code in Julia and then use it in Julia
The most stringet of engineering implementations using model-based designs is a MIL (Model in loop, i.e. raw simulink) -> SIL/PIL (software in the loop/processor in the loop) -> HIL (hardware in the loop)
really?
Oh, it seems so.
But I've heard that it's faster than Python. Is it? Wikipedia says it has a JIT/JAOT compiler
You want to test how your production code works in your model you have tow rite it yourself in Julia
Also, one of the biggest reasons for julia over matlab is that matlab is $$$
it uses type hints to optimize code and do multiple dispatch on it, but there is nothing ensuring your code is properly typed
Simulink can auto generate it directly from your model, and can even port it direct boards such as specific FPGA/Processors
julia is much faster than native python in almost every regards
Yes, there are industry matlab shops where the company is the one paying the licensing, but still
it's about as fast as numpy for numerics
When you design an aircraft or spacecraft, it generally has to work the first time or the consequences are fiery destruction. You simulate a lot. Julia enables not merely a flexible and fast way to write a custom simulation, but in fact an entirely new and powerful breed of si...
the performance imo is a non-argument, the main selling point is that you can actually write good old regular idiomatic julia and not depend on the quirk of a library
Well if you're doing that sort of modeling you're probably in big industry and have the money
(just a reminder: if this goes wildly off topic of python, let's move to #ot-*)
numpy becoming so prevalent is a curse but also a blessing, as if you know it, you know how to use almost every tensor library
I can't remember the last time I wrote a module that didn't import numpy
Very regularly, pandas can get done 90% of my work, which uses numpy but still I find myself not directly importing it
Simulink is pretty neat though, I'm a fan
But when my student license expired, that was it lol.
Yes, its expensive but most engineering design software is. Freaking any kind of EDA tool is going to cost an arm and leg.
I'd have to justify the license to my company and in good conscience I can't.
Because I can get plenty done with numpy/scipy
and pandas, etc
The problem with bare simulink in industry is that it isn't enough. So unless you want to shell out the money for the CodeGen support and application specific toolboxes its not worth it.
Yeah, precisely
The head of our science division has a license, and to the best of my knowledge he's it
and he can do codegen and all that jazz
Yeah, its really good if you do that. The turn around on implementations can be fast
I'm a little jealous with how much faster his algorithms run than mine, even though we have like the same implementation.
We're talking seconds, but still
Ive modeled digital fitlers and controllers have directly ported it do an FPGA of my choice, dictating where and how to use the built in DSP/FFT cores
Nice. I work quite a bit with digital filters and do a lot of dsp
Again its big $$$
Maybe it just depends on industry. I'm in neuroscience and we're pretty well funded, but maybe not as well funded as other industries.
This is getting off-topic though
for sure, interesting talk though : )
Definitely
can somebody tell me the use cases of partial functions in python?
mm, the way I think about partials is that they allow you to "pre-fill" some arguments to a function, while leaving others to be filled in later
let me give a super simple example, let's say we have this function:
>>> def say_hello(animal_a, animal_b):
... print(f"{animal_a} says hello to {animal_b}!")
...
>>> say_hello("Cat", "Bird")
Cat says hello to Bird!
now let's imagine that in some part of your code, you want to call this function many times, but animal_a will always be the same
we could therefore create a partial, which will automatically fill in animal_a, and will wait for animal_b to be specified
>>> import functools
>>>
>>> elephant_says_hi = functools.partial(say_hello, "Elephant")
>>>
>>> elephant_says_hi("Snake")
Elephant says hello to Snake!
>>> elephant_says_hi("Lizard")
Elephant says hello to Lizard!
now elephant_says_hi is a partial which when called, will pass "Elephant" as the first argument, and whatever you call it with as the second argument
however in practice I usually come across partials being used to "delay" the call to some function, but with the arguments already filled in
for example, if we do:
>>> say_hi = functools.partial(say_hello, "Elephant", "Dog")
say_hi will now, when called, call say_hello with those two arguments, so we can for example pass the partial as a callback to some other function
>>> say_hi()
Elephant says hello to Dog!
I hope that makes sense
for another use case, in one project that I worked on, I had a function return a dict mapping from ints to partials, and the caller would then choose the partial to call based on the key - the justification for this was that the function wrapped by the partial was very expensive, and it only needed to run once, but within the function I didn't know which arguments to use (because the decision partly depended on another function)
so I prepared them for the caller, i.e. "choose which one to call"
of course, this could have been avoided had the whole thing been designed better
i used them in my truthtable project for specific binops
And = partial(BinOp, 'and', lambda p, q: p and q)
Or = partial(BinOp, 'or', lambda p, q: p or q)
Implies = partial(BinOp, '->', lambda p, q: not p or q)
Iff = partial(BinOp, '<->', lambda p, q: p == q)
Xor = partial(BinOp, 'xor', lambda p, q: p != q)
could just subclass, but this was less typing
Actually, in Python, methods are kind of partial functions.
class Duck:
def quack(self, loudness):
print(f"{self}:", "qu" + "a"*(1 + loudness) + "ck")
dave = Duck()
dave.quack(42)
dave.quack works like Duck.quack.partial(dave)
>>> dave.quack
<bound method Duck.quack of <__main__.Duck object at 0x7fab47705b80>>
thanks @sacred tinsel
yeah so now I see them like less typing with the same functionality
Sometimes I wish lambdas are way nicer than what they are currently
always
smh I just want to be able to declare predicate functions inline without lambda all over the place
lambda p, q: p and q
-->
p and q from p, q
also pep 8 discourages lambda like
f = lamda x: x * x and opts for
def f(x): return x * x
is this due to readability?
Debugging as well
well, lambda's are meant to be anonymous -- if you're assigning them to a variable, you should use normal def
hmm so instead it is preferred to use them inside a function like map or filter
right?
usually
right
def logger(msg):
def log():
print('Log', msg)
return log
log_hi = logger('Hi')
log_hi()
Isn't this stub confusing? I mean why would you do that? I was reading about First class functions and closures btw.
my ipython console accepts λ
add this to your startup file:
import re
__λ__ = re.compile(r'λ[a-z]+[.]')
def __λ_sub__(m):
m = m.group()
return f'lambda {", ".join(m[1:-1])}:'
def _transform_λ(lines):
return [__λ__.sub(__λ_sub__, line) for line in lines]
get_ipython().input_transformers_cleanup.append(_transform_λ)
this expects a . after single-letter variables though: λpq.p and q
@unkempt rock Well, educational/explanational examples are often useless.
okay can you show me a real world example?
@grave jolt I've often used classes as partials in Java.
3.9 is launching in oct 5th apparently. Didn't Know that
Like, prepopulate certain parameters in the constructor and supply others on the fly through method arguments.
@unkempt rock example of what? first-class functions and closures?
yeah
do you want real world example of nested functions?
or this partial-like use of it specifically
nvm I will just skip this part and come to it later
@unkempt rock Have you already learned about decorators?
nah its still in TODO, the prerequisite was first class functions and closures.
Well, decorators and decorator factories are one application of nested functions.
And functions being first-class in general.
@unkempt rock In the case of logging, actually executing the log call, or constructing the log string, can be expensive, so you might only want to do that if the log level is set high enough.
So it would make sense to construct the function that creates the log entry in one place and running it in another (and only if it's actually necessary).
I see
Woah. Wait. Does Python's print() function use sys.stdout? And does Python's input() use sys.stdin?
here's a example decorator you might see in the wild:
In [15]: def run_once(func):
...: def wrapper(*args, **kwargs):
...: if not wrapper.has_run:
...: wrapper.has_run = True
...: return func(*args, **kwargs)
...: wrapper.has_run = False
...: return wrapper
...:
...: @run_once
...: def hi():
...: print('hi')
...:
In [16]: hi()
hi
In [17]: hi()
# No output
@lusty patrol Yes.
Dude.
you can redirect print with file kw
You can read from a file with input(), or from a string, or from a socket probably
Hello everyone, little question about typing.
so uh, I have a zip function in a class that has generic T
and so, when I write out with several types: python class Iter(Generic[T]): @overload def zip(self, __iter_1: Iterable[T1]) -> Iter[Tuple[T, T1]]: ... @overload def zip(self, __iter_1: Iterable[T1], __iter_2: Iterable[T2]) -> Iter[Tuple[T, T1, T2]]: ... @overload def zip(self, __iter_1: Iterable[T1], __iter_3: Iterable[T3]) -> Iter[Tuple[T, T1, T2, T3]]: ... ... and I can't seem to find a way to type it for a variadic amount of arguments
since Tuple[T, Any, ...] is not valid
yeah, i think overload only works for single dispatch
or maybe not
did you try it?
no like
not that
I have @overload everywhere
but the thing is, if you write like python def zip(self, __iter_1: Iterable[Any], __iter_2: Iterable[Any], __iter_3: Iterable[Any], __iter_4: Iterable[Any], *iterables: Iterable[Any]) -> ? it won't accept Iter[Tuple[Any, ...]] as the return type
telling that it is incompatible
i.e. Overloaded function implementation cannot produce return type of signature n
-> Iter[Tuple[Any]] doesn't work?
should be -> Iter[Tuple[Any, ...]], going by that logic
why
It unfortunately does mean a Tuple of exactly one element with type Any
either way, does not work
Example:
Tuple[T1, T2]is a tuple of two elements corresponding to type variablesT1andT2.Tuple[int, float, str]is atupleof anint, afloatand a string.To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g.
Tuple[int, ...]. A plainTupleis equivalent toTuple[Any, ...], and in turn totuple.
this is so infuriating lmao
that's inconsistent with the Iterators but ok
It's not inconsistent, no
Hello, I have a problem with the Visual Studio Code editor, namely Rich Presence does not start.
well tuple is not a true iterator in many langauges
since it is defined to be pretty much a well-known group of different types
@graceful junco that's a wrong channel for that
I was not answered in the main channel
Ok
another reason not to type things
hah
better to leave__annotations__ for esoteric meta classes
@cloud crypt based on the fact this issue is still open there doesn't seem to be a "neat" way to do what you want to achieve https://github.com/python/typing/issues/193
F
Does python release the memory once you del a object?
Arguably variable length tuples are semantically inconsistent
Maybe just do Sequence[Any]
if the refcount reaches 0, then yes @worldly pebble
in the final return?
Tuples are supposed to be for fixed/known length records imo
well zip is really a special case
The tuples are fixed-length, based on the input parameters
yeah
import pandas
df = pandas.read_csv('large_txt_file.txt')
del df
Let's assume the df size is 2gb
Does deleting is efficient
or is there some other way to free up?
a given function call to zip will only return tuples with size N
I mean, you are asking for dependent typing
Since the amount of args to zip can vary
@worldly pebble if that is the only code referencing df then it should free that memory
What if there is some processing between read and del? @paper echo
What type should
zip(*['123']*randint(1,10))
``` have
also you should not read the whole file instead read chunks by chunks ig
import pandas
df = pandas.read_csv('large_txt_file.txt')
Some processing on df
dictionary = {some_processed_parts_of_df}
del df
Is the above one more efficient
or
import pandas
df = pandas.read_csv('large_txt_file.txt')
Some processing on df
dictionary = {some_processed_parts_of_df}
df = pd.DataFrame()
Or doing implicit garbage collect
import pandas
import gc
df = pandas.read_csv('large_txt_file.txt')
Some processing on df
dictionary = {some_processed_parts_of_df}
del df
gc.collect()
if a SINGLE thing references to df, it won't be deleted
what if all the references are also deleted @cloud crypt
if you are sure about it, then yeah, it will be deleted
@worldly pebble you can't force something to be deleted at a specific time.
How do I handle it then
The gc.collect() version is the one most close to "perfect"
as it forces a gc-cycle
Thought So
How resource constrained is your environment?
If memory is really an issue you can disable garbage collection completely and write your own manager for the memory, this is what we did at our company
Because I have a huge csv file like 2gb
I am storing some transformations into dict
and I don't want to have a 4gb in usage
So how do i free up the csv file memory read as it's not required
gc.collect doesn't interact with reference counting
@unkempt rock you can do that in python? Or did you modify the C code?
and when a refcount reaches 0, it directly destroys the object
@teal yacht can we do it explicitly
@worldly pebble the 2nd makes more sense
yes, using del
del is simply obj.refcnt -= 1
Also I recommend experimenting. Just try it and look at memory usage
^
del doesn't guarantee that you've fully decrement the reference count
of course not, there's no way to guarantee that
but there's no way to guarantee anything in python, and we live with it
@worldly pebble the 2nd makes more sense
@paper echo Thanks
We had a chat a while ago about what it would take to have forced object deletion
It would be really bad, apparently
@paper echo you have to go in C to interact with the ref counting GC, I recall an article from instagram that did something with it to increase their performance by quite a lot
you either have to tank performances by scanning every objects to find every reference to the object you want to delete, or you directly free it, risking invalid objects later on
@cloud crypt If you really need something like this, you could use immutable linked lists :D
Tuple[int, str, str, *Any]:
V = TypeVar("V") # or something like that
Vec[int, Vec[str, Vec[str, V]]]
The implementation could actually use a contiguous array (i.e. tuple/list).
did I hear recursive annotation here haha
yeah 😎
from typing import TypeVar, Generic
T = TypeVar("T")
U = TypeVar("U")
V = TypeVar("V")
class Vec(Generic[T, V]):
def __init__(self, hd, tl):
self.hd = hd
self.tl = tl
def prepend(x: U, vec: Vec[T, V]) -> Vec[U, Vec[T, V]]:
return Vec(x, vec)
a: Vec[str, Vec[str, None]] = Vec("hi", Vec("hello", None))
b = prepend(4, a)
b is inferred to be Vec[Literal[4], Vec[str, Vec[str, None]]]
in Pyright, at least
Alternatively, you could just do a nested tuple (Tuple[int, int, str, Tuple[Any, ...]]) as a compromise
not like I can apply it in my Tuple[T, T1, ..., TN] case
T being a tuple?
can i take an object from a function that i'm decorating inside the decorator?
since the object only exists inside the function, and is not passed into the parameters
Maybe I’m misunderstanding but could you not do Tuple[(T: Tuple[Types])* n] or whatever the syntax would be for that
there is no such syntax
thing is, there is a fixed T and zip function which returns Tuple[T, ...] where ... is Any, ..., and it isn't compatible with T, T1, T2, T3 signatures
Could you not redefine them to fit the case?
Has anyone applied multivariate testing in python? ( Multivariate in the context of AB testing )
#data-science-and-ml might be more adequate for that question.
is it a good idea to call shell commands using subprocess.call?
wrong channel
not really, we are having a heated debate about it in #ot0-psvm’s-eternal-disapproval. Just wanted to know what the pros think about it.
Iirc subprocess.call is the standard for Python <= 3.5. Nowadays, you would use subprocess.run instead @covert saddle
@covert saddle what is the alternative? Calling shell commands with something else? Not calling shell commands? Using Popen directly?
if the shell command is Linux only, i tend to write bash scripts that run the python script, capture the output and then pipe it back to the script as an argument
but I don't know if this is the correct way to do it, and that's why I asked
i don't understand how that description relates to "call shell commands using subprocess.call"
I agree, i framed the question incorrectly. The subject of my question is calling shell commands from python scripts, not subprocess.call.
Shell builtins wouldn't be accessible from there... right?
Since the whole point is that it sends the arguments to the kernel and bypasses the shell
@cloud crypt i still think you should just use Sequence here
@paper echo well eh, not really... doesn't work kek
Why doesn't it work
do we have pattern matching yet 
nah
@paper echo Tuple[T, T1, T2, ..., TN] and Tuple[Any, ...] are not matching -- and so is not Sequence[Any]. In the end, @no_type_check will do I guess lmao
is there a library that can like for 15 or 10 times per second so its not intensive , check if part of a screen looks the same , maybe can even recognize text ?
not really #internals-and-peps, tbh
just, nevermind, it's not going to function that way, I tried it and it didn't work
Hi, can someone explain why I can't do f = lambda n: eval('all(n % i != 0 for i in [2,3,5])') to get a function that returns that n is not divisible by 2, 3 or 5? When I do f(10) I get "NameError: name 'n' is not defined". However g = lambda n: eval('n > 10') works fine to define a function that returns that n is greater than 10 and so g(10) returns False
And yes I explicitly want to use eval since I actually need to evaluate user provided strings
@shadow musk this isn't a help channel
@hollow crane Sure, same question for def f(n): return eval('all(n % i != 0 for i in [2,3,5])')
ah i see
i mean scoping with eval is kind of weird anyway
i wouldnt have thought your g example would work
g(10) works in my python 3.8.2 at least
@shadow musk Why are you using eval at all? 👀
eval accepts globals and locals as extra parameters, I think it doesn't receive information about the enclosing scope as well.
Oh, wait, the issue may be that a generator expression/list comprehension creates a new stack frame, so n is actually a nonlocal variable.
@grave jolt Hmm, so what about def h(n): return eval('n == 0 or h(n-1)') ? h(10) creates a new stack frame since it does a recursive call to h but this evaluates fine
I have no idea how eval works here. What you're doing belongs to #esoteric-python
eval('all(n for _ in "abc")', {}, {'n': 3}) fails too.
I'm inclined to agree, this seems specific to generator expressions and list comprehensions.
In [20]: eval('[n]', {}, {'n': 3})
Out[20]: [3]
In [21]: eval('[n for _ in "abc"]', {}, {'n': 3})
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
yep. ```
~>python2
Python 2.7.17 (default, Apr 15 2020, 17:20:14)
[GCC 7.5.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
eval('[n for _ in "abc"]', {}, {'n': 3})
[3, 3, 3]
it's probably related to the change that made comprehensions' loop variables not leak
yep <#esoteric-python message>
Seems like you cannot construct closures over non-global variables from inside eval.
f=lambda n:eval('lambda:n')()
``` also errors
this seems like a bug to me, honestly
kind of yes... everything in eval for which scope is not resolved should be looked up using LOAD_NAME
!e
s='Hello'
def print_(s):
return print (eval('lambda:s')())
print_('Bye')
@flat gazelle :white_check_mark: Your eval job has completed with return code 0.
Hello
This seems pretty buggy to me
In [30]: def foo():
...: n = 10
...: print([n for i in "abc"])
...: eval('print([n for i in "abc"])')
...: foo()
[10, 10, 10]
NameError: name 'n' is not defined
``` sure don't seem right.
whoa:
In [32]: def foo():
...: s = "abc"
...: print(eval('[c for c in s]'))
...: print(eval('[s for c in s]'))
...: foo()
['a', 'b', 'c']
NameError: name 's' is not defined
that makes sense to me 🙂
because the iterable is passed as an argument to the list-comprehension-function, not accessed as a nonlocal variable from inside of it
I mean, it doesn't really make sense and is a WTF thingy, but it is explainable
!e
import dis
def f():
return [c for c in s]
dis.dis(f)
god damit
4 0 LOAD_CONST 1 (<code object <listcomp> at 0x7f9c8a2aabe0, file "<string>", line 4>)
2 LOAD_CONST 2 ('f.<locals>.<listcomp>')
4 MAKE_FUNCTION 0
6 LOAD_GLOBAL 0 (s)
8 GET_ITER
10 CALL_FUNCTION 1
12 RETURN_VALUE
Disassembly of <code object <listcomp> at 0x7f9c8a2aabe0, file "<string>", line 4>:
4 0 BUILD_LIST 0
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 8 (to 14)
6 STORE_FAST 1 (c)
8 LOAD_FAST 1 (c)
10 LIST_APPEND 2
12 JUMP_ABSOLUTE 4
>> 14 RETURN_VALUE
As you can see from the first few lines, it's doing <listcomp>(s)
I mean, it doesn't really make sense and is a WTF thingy, but it is explainable
Yeah - I get why it is what it is, but I think it's pretty surprising from a user POV.
But my go-to core dev friend says it's supposed to be like that. 🤷
it seems really surprising to me for a single syntactic construct to have multiple distinct scopes. I get why it needs to be that way, but still - really surprising.
What is the purpose of ast
!doc ast
Source code: Lib/ast.py
The ast module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like.
An abstract syntax tree can be generated by passing ast.PyCF_ONLY_AST as a flag to the compile() built-in function, or using the parse() helper provided in this module. The result will be a tree of objects whose classes all inherit from ast.AST. An abstract syntax tree can be compiled into a Python code object using the built-in compile() function.
Yeah I read that, it means nothing to me
Yeah I read that, it means nothing to me
@swift imp an AST (abstract syntax tree) is a representation of code halfway between source code and bytecode.
if you could explain what you did not understand about the doc @boreal umbra linked, it might help
for the record, idk what ast is for either, I just like how you can link to the docs with the bot.
@swift imp if you want to write a program to process code, the ast gives you a structure to work with
Thank you, I see now
ParamSpec sure is interesting
So many peps about typing
Really like it, just think it's really a pity that duck typing is so prevalent
it kinda undermines the typing
imo duck typing should be considered bad practice. For other reasons too

Does anyone know R here?
Struggling with a line of code.... older plyr function I cannot figure it out
Structural subtyping + composition 
#ot0-psvm’s-eternal-disapproval @quiet stone
What's there even to gain with duck typing? Like, what do you lose by extending the proper abc(s)?
Structural subtyping would allow you to avoid inheritance entirely I think
polymorphism
because not everything has an abc
I don't get this argument. You can make an abc anytime you want
it is exactly what it sounds like
you create new functions that will do certain tasks and you use it with your existing functions.
Usually done for not repeating code and making your program more readable
@shrewd bolt however, this is not the right channel to ask that question
Structural subtyping would allow you to avoid inheritance entirely I think
So? There's nothing inherently bad about inheritance
inheriting from the proper classes create a meaningful "signature" for the class
and has a lot of informational value, much like the signature of a function
it's more powerful, since you have all the goodies of non abstract classes available
and can do stuff similar to default methods in java interfaces
Fair enough, although it can also be noted that not all libraries explicitly expose ABCs, but then again, there's already a reason why they aren't exposed in the first place
Similarly, mixin classes typically don't inherit upstream since they're supposed to hijack methods/super calls in the first place
it's more powerful, since you have all the goodies of non abstract classes available
@wet obsidian Inheriting from concrete classes is risky business... You as a user of someone else's class have no way of knowing whether it not correctly handles cooperative inheritance, or whether it will delegate to the wrong class instead of the next class in the MRO, or accepts arguments incompatible with the next class in the MRO, or things like that. Designing for correct behavior under inheritance isn't something you get for free, and it's something you can't assume all classes have done. And as inheritance hierarchies get deeper, it can often be tougher to make sure that the most derived classes are still Liskov substitutable for all their base classes.
It's not that inheritance is inherently bad, it's that there are a lot of gotchas to designing and maintaining correct inheritance hierarchies. Like, what happens if you subclass a class from a library, and you add a new attribute to your derived class, and later the author of the library adds the same attribute to their class with a different data structure, or something.
Inheriting from ABCs is safe, and does have some documentation value, but I wouldn't extrapolate from there to extending concrete types too freely.
Yay!
Ooh, and an Alpha of 3.10 with | syntax for unions, nice
yo i have a unclosed client session error with aiohttp and its annoying me ive tried everything someone help
Finally
It's listed as a coming feature on the "What's new in 3.10?" page
And the status is now accepted, niice
I definitely have complained about that exact same feature in the past month
I'm just a crybaby who can't use google
how does python3.9 typing work under the hood? it doesnt optimize variables, right? is it only for debugging?
They don't affect runtime at all
guys flask vs django
They're there for documentation and for type-checking tools like mypy or pyre
guys flask vs django
@unkempt rock Its a difficult long answer
Basically flask is a build from scratch thing, while django is batteries included
@unkempt rock Might be more appropriate to ask in #web-development, not really on-topic for this channel
@mystic cargo | for dict unions came in 3.9, 3.10 will introduce type.__or__ to allow you to write, say, int | str instead of Union[int, str]
I though it was already there for a while, no?
>>> a, b = {1, 2, 3}, {4, 5, 6}
>>> a | b
{1, 2, 3, 4, 5, 6}```
| for union, & for intersection, ^ for symdiff, - for diff, probably no complement though
I think there was a pep (or was it just an idea in the mailing list?) for universal sets, that would make it possible to get complement with, say, ~
yeah those existed
can someone help me find some resources for constructing qualitative spacetime models in using Python? things like: classes, github repos, notebooks, and so on...
Between Pandas, Numpy, Matlab, Scipy, ect.... which do you focus to learn first? Also, how long does it take to learn pandas, Numpy, MatLab?
Why Matlab in the middle there? (also, this is not the right channel for this question)
@spice pecan well... a complement wouldn't be a set anymore, right?
could still be useful, though
It could a subclass of set
Something along the lines of universalset, which inverts the membership tests and keeps the items that are excluded from it
Although it does pose a lot of questions, like "How would it be printed?" and "How would it interact with regular sets?"
Well, it would be a completely different data structure, I suppose. Because it would get messy when you | and & and ^ and - it with regular sets and other universal sets. Although you could store it as a tree of predicates:
!e
class Predicate:
def __init__(self, is_true, name="<anon>"):
self.is_true = is_true
self.name = name
def __call__(self, *a, **kw):
return self.is_true(*a, **kw)
def __repr__(self):
return f"<Predicate {self.name}>"
def __or__(self, other):
if not isinstance(other, Predicate):
return NotImplemented
return Predicate(lambda *a, **kw: self(*a, **kw) or other(*a, **kw), f"({self.name} | {other.name})")
def __and__(self, other):
if not isinstance(other, Predicate):
return NotImplemented
return Predicate(lambda *a, **kw: self(*a, **kw) and other(*a, **kw), f"({self.name} & {other.name})")
def __invert__(self):
return Predicate(lambda *a, **kw: not self(*a, **kw), f"~{self.name}")
def __xor__(self, other):
if not isinstance(other, Predicate):
return NotImplemented
return Predicate(lambda *a, **kw: self(*a, **kw) != other(*a, **kw), f"({self.name} ^ {other.name})")
A = {1, 2, 3, 4, 5, 6, 7, 8}
B = {3, 6, 9, 12, 15}
in_a = Predicate(A.__contains__, "A")
in_b = Predicate(B.__contains__, "B")
p = in_a & ~in_b
print(p)
for x in [2, 3, 5, 12, 100]:
print(x, "=>", p(x))
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
001 | <Predicate (A & ~B)>
002 | 2 => True
003 | 3 => False
004 | 5 => True
005 | 12 => False
006 | 100 => False
the realization of a universal set is strange
Like how do you know apriori what all the elements are
Well, you're usually working in some domain -- like real numbers, strings, players etc.; and the universal set is just your entire domain.
yeah but like
Its not like set theory where U\A where A is subset of U and U is universal set
like
U\A would give you everyhthing in U after removal of A
you cant realize that in a program
bc you dont know apriori what the elements of U are
I mean, it depends on how you implement sets. If sets are hash sets, then that, of course, is impossible.
If you implement them as functions T -> bool, then it's easy
Ive done something like
class UniversalSet:
def __contains__(self, other):
return True
...But then you may not be able to list all the elements in a set, which you might not need
but its not useful outsideof just satisfying a part of my program where I couldnt construct a finite set of values
If you can combine this object with other sets and predicates (like in my example), it could be pretty useful if you need some fairly complex conditions -- now you can work with conditions are first-class objects
eh
Well, I never needed that 🙂
Tell me what you're gonna do with a set or predicate that cant be done with straight boolean algebra, they all literally have the same base operations just described in different domains
wdym?
Well, yes, of course
if you're only concerned with checking membership, a set of T is the same as a function T -> bool
I'd love to see applications of it being useful
well, I haven't seen any application of it per se, I just pulled it out of my ass
...as an example of how sets with ~ can be implemented
I think the absence of ~ for sets is due to the fact that the majority of complementary operations for mathematical sets i.e. ~ devolve into either the empty set, universal set, or some set difference involving the unversal set and given that you can't have a universal set when your sets are based on hashes theres no need for it
anyway im rambling
I suppose it is possible to construct a universe U in programming and have fullblown set notation for that would be cool as hell
thinking like
some parent class that has a __init_subclass__ that verifies every element of child is in parent and then you can have that fun
Does anyone know how to find a peek in a 2dimensional array
@stiff gust this channel is meant more for discussion. #algos-and-data-structs is a much better channel for that question
I'm very surprised to learn that pypy is written in python. How can pypy be generally faster than cpython, given that pypy is written in python and cpython mostly written in C? how can scripting language be faster?
@forest flicker the algorithm is more important than the language.
PyPy is a JIT compiler.
pypy turns the code that it runs into machine code. CPython does not do that.
So why is pypy not the canonical implementation?
pypy lags behind cpython on versions
I think its only 3.6 rn
plus pypy doesn't work well with c extensions and short programs
Also is the speed improvement that big of a deal for like 90% of users?
Pretty sure pypy also has worse startup times, so worse for short scripts
plus pypy doesn't work well with c extensions
It needs to emulate CPython's reference counting and API just to make C extensions work, and that emulation makes it slower than CPython for running those extensions.
Which has the paradoxical effect that the libraries where performance mattered enough to make them as fast as possible in CPython are the exact libraries that are slowest in PyPy.
So effectively it’s faster for heavy work being done pure Python?
Aye. At the end of the day, effectively heavy work is usually "outsourced" to C or something similar, so Cpython wins out simply because you're no longer running number crunching through native python anyways. (native python being the area where pypy smokes Cpython)
Well in pypys case yes
@radiant fulcrum I mean that is what we were discussing...
Yeah but it's the discussions between PyPy vs cpython,
C lib will still be faster than anything PyPy could reasonably do
Is it safe to assume that the memory layout of data in PyPy is incompatible with that in CPython?
is the memory layout not an implementation detail? i don't see how this could be an issue in any code
(but also it's always safe to assume incompatiblity)
C extensions need to be recompiled for PyPy in order to work. https://www.pypy.org/compat.html
from what i can gather, they're incompatible
Just curious, it would be fun if you could have a %pypy magic in iPyKernel
But that would be kind of silly if you had to copy data from one runtime to another
Is there an equivalent of sys.modules but for spec's? (Not sure Python internals actually need to store it some where, but perhaps it does and if so, I'd like to find them)
I have an eazy question...
does the ** operator basically mean "give me all of the entries from this dictionary"? that's what it seems like, but i just want to be sure lol
when calling a function, it unpacks a dict into keyword arguments:
args = {"a": 1, "b": 2}
myfunc(**args)
This is equivalent to:
myfunc(a=1, b=2)
it gives a dictionary of all the arguments passed, I think
it can be used in a function signature as well to capture all kwargs (that don't have a corresponding parameter) into a dictionary:
>>> def myfunc(a, **kwargs):
... print(f"Received a: {a}")
... print(f"Kwargs: {kwargs}")
...
>>>
>>> myfunc(a=1, b=2, c=3)
Received a: 1
Kwargs: {'b': 2, 'c': 3}
this means that your function can take arbitrary keyword arguments
notice that a is not in the dict, because the function takes a param named a, only those that "remain" will be captured into kwargs
i was asking because i know that's the syntax for kwargs, and i came across a way to merge dictionary entries into a single dict by just doing:
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
dict3 = {**dict1, **dict2}
It's not really an operator
It's special syntax that is recognized in a handful of places
But yes in general it means something like "unpack keys and values from a dict-like thing"
Or exponentiation, when it's used as a binary operator, heh
And gives correct results for some numbers 
God I've had some unfun debugging involving that
python 3.9 has a new way of merging dictionaries @minor sinew dict3 = dict1 | dict2
With pandas_datareader, what is a free service to use that dosnt need a key?
Are there any plans to allow using * and ** in comprehensions? i.e. ```py
a = [[1, 2], (3, 4)]
b = [*item for item in a] # Not possible currently, would love to have this
print(b)
[1, 2, 3, 4]```
Currently, this produces a SyntaxError:
>>> [*item for item in [[1, 2], (3, 4)]]
File "<stdin>", line 1
[*item for item in [[1, 2], (3, 4)]]
^
SyntaxError: iterable unpacking cannot be used in comprehension```
you can use nested comps, so it is not a high priority I would think
Unfortunate, IMO it'd be a big improvement
This does work, but I feel like * would be more flexible
>>> a = [[1, 2], (3, 4)]
>>> b = [v for item in a for v in item]
>>> b
[1, 2, 3, 4]```
I have to admit, I simply can't understand flat nested list comprehension kind of things
Just write the regular for loops in the same order
what helped me was formatting it like so
[v
for sl in l
for v in sl
]
``` and just read top to bottom
except first line is last
for v in item:
if predicate:
result.append(expr)```
i personally just dont use list comprehensions if i need to do more than like 2 things
Equiv to [expr for item in a for v in item if predicate]
it gets too jumbled up imo
I find that 2 at a time when the second one just creates multiple values is fine, but it can get horrible for sure
concat=lambda x,y: [
x
for x in [x[:]]
for yv in [[y]]
for _ in y
for a,*b in yv
for _ in [x.append(a)]
for yv[0] in [b]
][-1]
i can see why some people dislike making apis now lol
I mean this would be terrible even with regular for loops
@spice pecan Python has an external package called more-itertools that handles a lot of these processes involving lots of iterations. There's one called flatten that does what you are asking
https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.flatten
I know that, it was just an example - I'm still rooting for that syntax to be legal
ah gotcha!
is there a way to set custom variable names like we set custom strings with .format()
like is there a way using some library or it just can't happen
@gusty marsh This is not a help channel. See #❓|how-to-get-help
I don't really understand what you want -- can you elaborate or give an example?
so like (this is just an example):```py
#so if i set this variable
x="Abc"
#i want to do this
2{x}=1234
#that means
2Abc = 1234
there are ways to do that
but don't
use a dictionary or something
and 2Abc isn't even a valid var name
it is possible with more effort, but ew
how?
i got one way with dictionary but how to do without that
whatever = {}
x = "yes"
whatever[f'2{x}'] = 1234```
Variables are dict keys under the hood
You can access it with __dict__ and do some wonky stuff with it, but you really shouldn't
you could access locals itself but thats a dict anyway so why not just use your own dictionary
dynamic names aren't something you should really be using, maybe in the case of some classes and their attrs but it's confusing even then
@gusty marsh The whole point of a dictionary is to associate names with values dynamically.
So there's nothing wrong with just using a dict.
any other method is just the dict method with more magic
Anyway, this is not a help channel.
is Guido van Rossum in this server?
hey im looking for someone interested in helping me make a very flexible learning AI for now its very simple but i will probably enhance it in the future
@scarlet pumice @floral forum This is not a help channel and not #community-meta, please read the channel description. For meta stuff use #ot-* or #community-meta, check out #❓|how-to-get-help if you want to get help with Python.
@scarlet pumice if you're searching for collaborators, try #python-discussion or an off-topic channel
ok thanks
curious how it's decided that assert is a keyword assert 1<2 instead of a function like assert(1<2)
hmm.. actually both works
I wonder if it's because assert(1<2) is parsed as assert (1<2)?
yup
assert is a keyword so that it has no deeper stacktrace
much better than sys._getframe
yo im having errors with my shit im basically tryna figure out what do u add to await member.edit(name=rename_to) for it to rename someones nick name like their name, but then the thing after it so lets say someone was named callum and i did !nick @callum lol it would make it callum lol not just lol
this isn't a help channel @unkempt rock you might have better luck in #discord-bots
@minor locust assert is special because assertions can be turned off. So if assertions are off, the code after assert won't even be evaluated.
does collections.UserDict inherits from dict?
On a related note, and you might already know this, but there's nothing you can do to stop people who are running your code from turning them off. So you'll never want to write something that depends on assertions.
@unkempt rock I'm on my phone and my phone is almost literal garbage, but you can follow the docs to the source code. I tried and my phone froze.
!docs collections
Source code: Lib/collections/__init__.py
This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.
Oh here we go. https://github.com/python/cpython/blob/b664a1df4ee71d3760ab937653b10997081b1794/Lib/collections/__init__.py#L1040
yep
Looks like it inherits from something else.
i was looking into it
the mutable mapping comes from the default mapping
and the mapping from collection
collection from sized, iterable, container
i was wondering it because UserDict also have the dict _missing_ method
I thought dict didn't have dunder missing
@boreal umbra well, here is it, then i wondered that the dicts from collections inherits from this dict
even if the item doesn't exist, _missing_ is not automatically called
well how does it determine if item exists?
does getitem have to return something funky
@hollow crane it depends on how __getitem__ is defined for a given class. Are you working with lists or dicts? Or something else?
was referring to the example
i guess maybe if you define getitem it assumes you know what you're doing
if it raises KeyError
The actual lookup table for the dict is in C
wait no i'm wrong
I don't believe it's possible to interface with the lookup table in pure python so I think you have to inherit from a class that can, like dict
or call it explicitly, meh
Call it directly?
you can do self.__missing__(key)
!codeblock
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
Why not just use in?
im very very new to python and I was wondering if it is possible to like my teachers messages, basically my schooling system uses an online platform to display our grades. On this platform they can also send messages, in order for them to take attendance we must like the message they send out that day before a respective time on mondays(we don't have school on mondays but they still take attendance) basically I want to know how I can make a bot to like all their messages on monday when they come out. Thank you! 😄
Is codeacademy good to start learning python?
python v3.9 recently was released. What are the new features that excite you?
str.removeprefix
Is that really that much of a benefit?
Those funcs are getting touted but they don't exactly seem to add anything new
The stated benefit was clearing up confusion about rstrip and lstrip, and adding common functionality people have been implementing themselves
also set operations for dicts
and enabling type annotations like list[int] whereas before you needed typing.List[int]
pep 593 is weird to me, but i guess i see the benefit... that is one thing i do not want to use in my code
although this is an interesting use case https://www.python.org/dev/peps/pep-0593/#lowering-barriers-to-developing-new-typing-constructs
oh yeah, the new parser is very exciting
and zoneinfo is very very nice
why is this in the advanced discussion channel
@quick oar the channel topic is
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.
This is about as on-topic as you can be for this channel
I'm by far most happy about the zoneinfo. That's something that's way overdue for Python. The language has had the concept of a timezone for a very long time, but to actually represent a timestamp in some real timezone you've always needed a 3rd party library. This is something that very obviously should be supported by the language itself.
I'm by far most happy about the zoneinfo. That's something that's way overdue for Python. The language has had the concept of a timezone for a very long time, but to actually represent a timestamp in some real timezone you've always needed a 3rd party library. This is something that very obviously should be supported by the language itself.
@raven ridge it's honestly actually ridiculous and at odds with the batteries-included philosophy
makes a bit more sense when you realize that timezones are a nightmare and can potentially change at any time when some country decides to change it up
nah, that's exactly why I don't want a 3rd party library to be in charge of it. Having Python provide it, and having it hook into the OS's database wherever possible (since it's kept up to date by automated updates), is way better than needing to rely on remembering to pip install an updated 3rd party module to get it.
i don't think it was good, i just think it makes sense how the can got kicked down the road so far
yeah. I get that it's a hard problem to solve, for sure - and that's exactly why I'd rather it be solved in a single consistent way for everybody, in the part of the ecosystem that's best vetted.
now the really hard problem... convincing your boss to upgrade Python
I never really understood the fuss over timezones
Do people actually use location offsets instead of just using UTC with a numerical offset?
humans typically don't use UTC
so if you are trying to communicate a time with a human... you need it in their time zone
Do you?
this sounds like the unicode debate
no