#Proposed
for x in [1, 2, 3], y in [4, 5, 6]: pass
#Current
for x, y in itertools.product([1, 2, 3], [4, 5, 6]): pass
#Proposed
for i in range(5) if i > 2: pass
#Current
for i in filter(lambda i: i > 2, range(5)): pass
for i in (i for i in range(5) if i > 2): pass
#Proposed
return 5 + 5 if 4 > 2
#Current
if 4 > 2:
return 5 + 5
#internals-and-peps
1 messages Β· Page 51 of 1
I also think that for x in xs, y in ys is pretty nice, though having a zip equivalent should exist too
oh cool! Sounds fun to play with the parser
@brave badger what would a zip equivalent be like
Well you shouldn't put multiple things on one line in the first place, can't say I'm a fan of if cond:\n return ... if it's simple but the inline if doesn't look much better
I'm a fan of return ... if cond over if cond: return ...
i recently got mad at someone in review for having an inline if in c#
so ya no i dont like it here eitehr
In Haskell there's three different ways to do list comps
-- regular list comprehension
a = [(x,y) | x <- [1..5], y <- [3..5]]
-- [(1,3),(1,4),(1,5),(2,3),(2,4) ...
-- zipped list comprehension
b = [(x,y) | (x,y) <- zip [1..5] [3..5]]
-- [(1,3),(2,4),(3,5)]
-- parallel list comprehension
c = [(x,y) | x <- [1..5] | y <- [3..5]]
-- [(1,3),(2,4),(3,5)]
zipped list comprehension is basically the same as python zipped list comprehension
how about this for zip?
for x, y in i1, i2:
print(x, y)
the if after the return just looks confusing to me because I expect a return to be just that - a return, with an expression on the right
@digital briar that's used for tuples
actually wait
@digital briar yep, that's already used in Python
for x, y in i1, i2 iterates over two lists of two items, i1 and i2
There we go
??
@worldly venture Did you make it work differently with tuples?
let me send code
ah yes
you should check that and see if it's greater than what it would be without the (
hmmm
How should it look when separated to multiple lines?
for (
foo in [1, 2, 3],
baz in [3, 2, 1],
xyz in ['x', 'y', 'z']
):
print(foo, baz, xyz)
unfortunately
but uh
lmfao
for foo in (
[1, 2, 3],
bar in [3, 2, 1],
baz in [2, 4, 6],
qux in [3, 6, 9]
):
print(foo, bar, baz, qux)
that would work
I mean, if the need to do that ever arises you're probably a few loops too deep already so it's kinda bad form
what's the goal here? i'm confused
to have fun with Python?
syntax sugar for nested loops @red solar
that too
oh
I want to make an extended Python with a lot of sugar
and more powerful lambdas
but I don't know how to edit the grammar for it to work
it literally just looks like you're getting rid of the repeated for keyword - nothing else is changing
is that really a worthwhile improvement?
Actually, a slight one
lol, runs
But the goal is just to have fun messing around with Python.
@red solar I'm just doing it for funsies
exec(compile(source, "<ast shittery>", "exec")) epic
lol
A bit of an interjection, but since we're talking about syntax, thoughts on https://mail.python.org/archives/list/python-ideas@python.org/thread/G7CXCVJGR54QG5DES54R3P5GQX7COSUI/ ?
it works because python treats that source syntax as ```py
for foo in ([1, 2, 3], bar in [3, 2, 1], baz in [2, 4, 6], qux in [3, 6, 9]):
print(foo, bar, baz, qux)
@brave badger That's basically a switch case
interesting
Isn't pattern matching more powerful than just a switch case?
"switch case" as in the one most languages have is strictly for same type same length stuff innit?
pattern matching allows for more unreadability flexibility
Guido replied
This might be added
Proposed*
They're proposing it right now
They're using case instead of as
and match instead of try match
yeah I prefer that
is that nested foo shortcut a new feature?
I think it'd also be nice if dataclasses can generate the dunders needed for pattern matching
Only in Joethon
so basically
match result:
case ONE: ...
case TWO: ...
case THREE: ...
else: ...
something like this
is what they're proposing
@tacit hawk it is not, it's just exploiting python syntax to provide that
oh boy i hope they're not going to try and add match/case as a keyword
!pep 3013
PEP not found
PEP 3013 does not exist.
@red solar Guido is working on a proposal for it
https://www.python.org/dev/peps/pep-3103/ I wonder what changed since
yeah i read the post
he knows what he's doing, but i can't imagine how he's gonna do it without a keyword
i saw the as
but it seems hmm
he knows what he's doing, but i can't imagine how he's gonna do it without a keyword
overload more operators!
The new parser is the change that brought some propositions, a print statement was also mentioned somewhere a week or so ago
A print statement?
no way they switch print back to a statement lol
We can't be adding that back.
Also calling unary functions without the parentheses
@last pollen what make unary => operator?
no, => is best for functions
https://mail.python.org/archives/list/python-ideas@python.org/thread/NCQX6ZIBREUTLS52VVG3DSZ43OEXJFTT/ for a print statement and func calls without parentheses
x => 5 + x >>>>>>>>> lambda x: 5 + x
Stuff like
len "hello"
ord "g"
Also calling unary functions without the parentheses
that just reduces readability imo
yeah, I agree
then again python mature consenting blabla
yield could become a function
so it wouldn't really hurt to have that as an option
Haven't been following it but at least doubt that a parentheses-less calls will go through into an actual PEP
It's an equal level of horribleness
Well I'm sure yield is a reserved keyword
they aren't talking about paren-less calls any more
they aren't talking about paren-less calls any more
readability concerns? or just something not needed in the language?
i didn't follow it closely, but it seemed like kind of a non-starter
guess I'll add that thread to my reading list
Oh yeah that got shot down quite hard
I don't see the need for a print statement but I'm sure there's more thoughtful discussion about that in the mailing list
call without parentheses confuses with value access, no?
I don't see the need for a print statement but I'm sure there's more thoughtful discussion about that in the mailing list
Not really, most people said exactly that.
that was really just the same person posting under different accounts, everyone else loved the idea
Is there a way to get this functionality?
class Parent:
def method(self, start=None, end=None, frq=None):
if start is None:
start = self.start
if end is None:
end = self.end
if frq is None:
frq = self.frq
do_stuff()
class Child(Parent):
def method(self, start=None, end=None, frq=None, new_param=None):
# if start is None: <-- Get this for free?
# start = self.start
# if end is None:
# end = self.end
# if frq is None:
# frq = self.frq
if new_param is None:
new_param = self.new_param
wow, free, greedy are we
also
Does super run all of the code in the Parent class, then the code in the child class?
and would those local variables in the parent class end up in the child class? i.e. would the local variables (start, end, frq):
if start is None:
start = self.start
if end is None:
end = self.end
if frq is None:
frq = self.frq
be set in the child class?
super().__init__() runs parent init code
@fossil jetty the attributes (not variables) are in the object (not the class)
super delegates to the next class in the MRO, which isn't necessarily a parent class of your class.
https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ explains this in detail.
here is a very minimal example of my problem:
from dataclasses import dataclass
@dataclass
class Parent:
start: int = 1
end: int = 2
frq: int = 3
def method(self, start=None, end=None, frq=None):
if start is None:
start = self.start
if end is None:
end = self.end
if frq is None:
frq = self.frq
return sum([start, end, frq])
class Child(Parent):
def __init__(self):
super().__init__()
def method(self, start=None, end=None, frq=None):
super().method(start=start, end=end, frq=frq)
return sum([start, end, frq])
My expectation would be Child does the same thing as Parent (assume MRO is just a line up)
Instead, I get this behaviour:
I just want to move this:
if start is None:
start = self.start
if end is None:
end = self.end
if frq is None:
frq = self.frq
into the child class without having to rewrite it
This isn't on-topic for this channel. See #βο½how-to-get-help
Do you all think it would make sense for Python to have a list "view" feature? Kind of like slicing, except all the references aren't copied.
what would be a usecase for that?
Modifying a sub-list
Yeah seems niche
I just wish numpy and pandas had more explicit semantics around views
Wouldn't there be a performance benefit?
What if you just need to iterate one?
Item isnt copied though
But the reference still is
the reference is a pointer
copying it is basically free
(sure incref and whatnot but still)
It copies the entire list though
if you had a view you would still need to incref
Well, everything past 5
What would you want? to be able to assign to item and modify the value thats stored in the list?
Seems like a valid performance optimization for cpython I guess
It's just a performance thing, to save memory
Theoretically you could write a C extension listview() or something
i'm confused as to how a list view would work - you have a reference to said list? that's it?
Or maybe not
wouldn't it still call the original list's iter method through the view?
@red solar like slicing a numpy array but theres no guarantee even there that you arent copying pointers
Maybe but the point of my question is if it should be a standard Python feature
oh
class SequenceView:
__slots__ = ("_seq", "_offset", "_step", "_size")
def __init__(self, seq: MutableSequence, offset: int = 0, step: int = 0, size: Optional[int] = None):
self._seq = seq
self._offset = offset
self._step = step
self._size = size
@charred wagon something like this?
Yes, I suppose that would work just for iteration. I think being able to mutate it would be cool but it's a more niche use case.
you can mutate this, this was more a question of what information it would carry
Yeah basically like a slice, but it's a view
i've wanted listviews before, and still do
though islice can sort of do most of things i want it for
I could live without a step though. May make the implementation simpler too
The problem with islice is that it will iterate to skip stuff
should probably default to 1 π
yep
thats the worst part of it, but its a high performance skip
islice doesn't work on indexable types?
It treats it as an iterable
might be able to do something with stride_tricks
What's that?
this is so much simpler in c/c++, you just have a pointer and a size π
stride_tricks isn't really well-documented, but it moves through memory
seems like you could use it to make a view
I'm pretty it would have to be implemented as a C extension
Or make use of something that is a C extension
Which yeah, would in turn work with the pointer as you say
Maybe it's not so trivial, what do I know
what was wrong with my earlier idea? it works with any sequence type
point was to save memory, not create more overhead
less memory overhead, less computational overhead, pick one
views are a pointer and a size - in python that's PyObject * self._seq and PyObject * self._size
ohh
i see
the pointer can point to any element, whereas we need an offset to do that :/
but still it's like 1 extra pointer, and negligeable overhead
with stride_tricks, you could point to the start location and then just move along the array by the step size
so you could only iterate through it once?
that's not really a view
it's a single use iterable
i'm confused, what information does stride_tricks store?
a pointer to the start location, and the step size? nothing else?
opinions on private attributes/functions in python?
I think it would be a fine thing to have to be honest
π© Constants would be nice for debugging every once and a while
The protected convention with an underscore is fine enough as it is to be honest
constants are usually written capitalized
yeah
but thats all well and good until it starts changing and theres 15k lines of code that could be doing it
xD
saying that i think the issue i got when that happened was a race condition rather than stuff being overrode
Do linters pick up constants being modified?
dont think so
Pycharm didnt atleast
but it was a pretty big slew of code with the const being used by alot of things
what's a good way to sync up some code to a precise timer?
let's say I have something running on main thread that I want to loop every 1/120th of a second, but nothing more and nothing less, while the function itself takes a variable amount of time to run
would it be better to have an inner loop that waits for the time to be over, or instead should I use a second thread that unlocks and relocks a lock every 1/120th of a second
That sounds like an incredibly tall order to me.
The operating system's scheduler will not wake you up with sub-millisecond accuracy. And there is no guarantee that your thread will be scheduled, and won't be preempted, during that sub-millisecond window. If you need this to predictably run exactly 120 times per second, I promise that you will not get that working without an RTOS.
Or a microcontroller or peripheral dedicated to doing only this job.
Or by writing it as a kernel module / device driver, perhaps.
Although i have a proven algorithm. Each loop if it hasn't been exactly 120ms, skip and try again
Yeah I imagine the average call frequency is more important than gap between calls
i am not sure what cloud service to use
I have a dashboard, and I'm looking at the free tier on AWS
but I'm not sure which "type" to use
idk if i need aws glue
Try #tools-and-devops @signal bear π You'll have more answers
thx
on a side note, looks like python has a crontab module
I am curious if i can run a certain function from a .py file using the module, or if it would default to running the whole script
i was considering using crontab to schedule an extraction of data from a github page
basically im just trying to update the dataset im using, I don't know if it would make sense to run the whole script again, or if I should just try to run the function that extracts the data
probably one for the python general channel, but in short adding a command line flag to the script that runs just the refresh part would be what i'd do.
Hmm guys i think i need a help or somr guide or the way to understand docs more, i am more comfortable with yt tutorials but i think reading docs is better, what is good way to move from yt tuts to docs?
Especially real devs dont have time probably to watch 3h of yt content that thry can check in docs
@ocean igloo Perhaps pick a module or project you're already familiar with, and look at its documentation to see how the ideas in it are communicated in the docs
or, pick a module or project you'd like to work with starting from scratch, and give the docs a slow once-over. A project that has examples or a tutorial is a good place to do this with (e.g., Django, which is big and has tons of moving parts, but has a fantastically detailed tutorial and excellent docs).
But your instinct to transition to reading docs is a good one, because teaching yourself how to parse project docs is a powerful skill.
@ocean igloo For future reference, this channel is meant to be used for indepth discussion of the Python language. You can ask for help or advice in #python-discussion or a help channel ( #βο½how-to-get-help )
Did anyone see the proposal about a try match block? I don't understand what functionality it's adding.
But how is it better than if-elif-else?
Presumably there's some kind of hashing operation so that the match can be done that way instead of needing to traverse the entire chain of matches, but I'd have to see what GvR is proposing in detail.
I see
wait is it a case switch PEP?
To my mind that would be the only real advantage: have some kind of dict-under-the-hood-style matching going on, because otherwise you just have syntactic sugar for if/elif/else
It looks similar to case switch but the PEP isn't up yet
I like having syntactic sugar except for the name of that concept.
I also hate "pythonista"
lmao
you mean you don't like syntactic sugar or you don't like the naming of try match?
I don't like the phrase "syntactic sugar". Something about it rubs me the wrong way
right
but I think trying to extract more use cases out of existing keywords is fun.
I misspelled it as "synthetic sugar" and "syntax sugar" for a looong time
the first one sounds a little too everyday
syntactic sugar is perfect
the latter is unnecessarily specific
Sugar only makes things taste/feel better
that is what syntactic sugar does
e.g. you could write promises which are ugly asf on js, but now, you can use async/await
so much nicer
Imagine there used to be a time when f-strings didn't exist
I've grown so used to them now
pre-3.6 was dark times
man speaking out facts right now
only 90's kids will remember %-formatting
% formatting made me so sad
but I guess it's better than unreadable chains of + signs
tbf i still use .format alot
pypy especially seems to have moments where it goes holy fuck what are these weird f thing
@boreal umbra I'm not sure what the proposal looks or will look like, but a switch-case does not necessarily behave like an if-elif-else since all cases below the triggered one are executed (I think there are languages where that isn't the case, but it is in C and Java)
For example, pseudocode:
switch (x)
case "A":
print("A")
case "B":
print("B")
if x == "A" then we print both "A" and "B", a break is used to stop the fallthrough (often you see each case end with a break)
there are some very attractive optimization possibilities which I'm generally not smart enough to understand but they likely wouldn't apply to Python
Ah I see
I don't know that I like the implicit fallthrough though
Did anyone see the proposal about a
try matchblock? I don't understand what functionality it's adding.
[....]
It looks similar to case switch but the PEP isn't up yet
@boreal umbra that was my take as well. it read much like aswitch. it was also funny that GVR had already worked on it as well with the new parser.
I hope it will go more the route of ML pattern matching than C imperative switches
wdym? (not familiar with ML pattern terminology)
like using approximation and probability? throwing darts... π
import constants
match config:
case {"route": route}:
process_route(route)
case {constants.DEFAULT_PORT: sub_config, **rest}:
process_config(sub_config, rest)
``` something like this (from the new PEP that just popped up)
ahh. didn't see the PEP. nice!
Is __init_subclass__ called before or after the metaclass' __new__? Are they just incompatible?
just got an answer in #help-falafel
Hey there's the PEP!
really? what number?
protocols?
oh god we are going to get so many "why doesn't case work" questions from people who know other programming langauges
!d g typing.Protocol
class typing.Protocol(Generic)```
Base class for protocol classes. Protocol classes are defined like this:
```py
class Proto(Protocol):
def meth(self) -> int:
...
``` Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:
```py
class C:
def meth(self) -> int:
return 0
def func(x: Proto) -> int:
return x.meth()
func(C()) # Passes static type check
``` See [**PEP 544**](https://www.python.org/dev/peps/pep-0544) for details. Protocol classes decorated with [`runtime_checkable()`](#typing.runtime_checkable "typing.runtime_checkable") (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures.
Protocol classes can be generic, for example:
```py
class GenProto(Protocol[T]):
def meth(self) -> T:
...
``` New in version 3.8.
ah, neat
i really wish we had better support for generics though
as far as i know, you can't currently define types like A[B] in a way that mypy can understand
like if you wanted to define a tree where the data contained only ints, you can't write a Tree class such that Tree[int] does what you'd want it to do
(at least, that i know of)
I wonder if we will ever get something like flow (JS inferring, partially dependently typed, type checker)
you maybe can with typing.conditional and make the check yourself or sth. But it does kind of defeat the point
typing.conditional?
help i am having errors
ah, nvm, I am misremembering
what i would really like is for mypy to be able to identify that
class MyRecord(TypedDict):
name: str
age: int
is a subclass of
Dict[str, Union[str, int]]
and booo generics are excluded from pattern matching
so much for this:
case List[str]:
i can see why but still
will this work with something like
case None:
...
case .math.nan:
...
? seems like no because it uses == internally for literals
match statement would be quite interesting, but i'm still waiting for a none-aware operator
that would be nice
probably won't happen though
dict merge made it in, I think this is about the same
!pep 505
deferred unfortunately
dict merge ++
the maybe-. and maybe-[ are clever
i wonder if this has value though
the walrus operator already covers a lot of use cases
and we don't want to end up like raku or haskell
operator salad
Not something we're going to help with on this server
solving image recaptcha is not quite possible anyway
Heck, humans fail recaptcha π
voice captcha solving is somewhat feasible
there are some nice attempts on it
what does pure python mean in this context if you will need AI
It doesn't matter. We're not assisting.
and even if we were, it would be off topic for this channel π
I dislike that PEP 622 proposes making _ not bind a variable. I get why they're doing it, but it feels inconsistent to make it special like that... π
inconsistent how?
isn't it fairly common to use _ as a placeholder?
i think go even enforces it
it's common in Python today, but when you do it creates a real variable named _
but the whole point is that you never use it
that is, it's convention that makes it a placeholder, not language semantics. This would be inconsistent with other uses of _ in the language today.
!e
_, _ = 1, 2
@raven ridge :warning: Your eval job has completed with return code 0.
[No output]
yep.
Other languages have done it because it reduces memory allocation I believe
Couldn't Python benefit from that too?
not sure it would benefit in any significant way
saving what memory?
since rn _ would just be PyIncref(obj); PyObject * new_obj = obj;
the usual benefit of a switch statement in a C-like language is that the cases aren't evaluated linearly. This proposal won't have that benefit.
are we talking about _ or switch?
we're talking about PEP 622 - https://www.python.org/dev/peps/pep-0622/
[*_]matches a sequence of any length.
I think it needs something to be reserved in order to make that possible.
they couldn't introduce a new singleton type?
* could have been the wildcard, and would have been a better one IMHO, but that won't work for a wildcard sequence of any length.
Any is literally what they want
i agree that elevating _-as-placeholder from convention to language spec is unsettling
is the pep still open to changes?
the PEP could also use some reworking to make sure that the examples don't use syntax before the section explaining that syntax, heh
yeah, this is just a proposal at this point.
ew, I hate the example for https://www.python.org/dev/peps/pep-0622/#id7
I do python now
maybe the real python was the friends we made along the way
To match a sequence pattern the target must be an instance of
collections.abc.Sequence, and it cannot be any kind of string (str, bytes, bytearray).
That's weird too - this would be the only context I can think of where a string cannot be unpacked exactly like a list...
what about memoryview? does that count as a string?
@raven ridge yeah i dont like that either
id rather add a collections.abc type that's a "Sequence but not a String"
can it match List[str]?
of course; nothing in the PEP says that it couldn't.
so what's the issue with str? you can essentially treat it like List[str]
the issue is what I said - in a normal Python context, you can do:
a, b, c = "abc"
print(a, b, c)
``` but in this proposal, you would not be able to do ```python
match "abc":
case a, b, c:
print(a, b, c)
``` even though you could do ```python
match ["a", "b", "c"]:
case a, b, c:
print(a, b, c)
``` so it's inconsistent with other ways that a string can be unpacked.
This has a few strange limitations that I hope they figure out but I really like this overall
but i don't see why that has to be a limitation?
I'm sure the mailing list's got an answer somewhere 
Python is getting case statement things?
maybe
the formal proposal for it has landed; we're discussing that proposal. https://www.python.org/dev/peps/pep-0622/
Guido the madlad actually did it
the only reason i can see Sequence not containing Str is for pandas/numpy compat
which i think is... not right.
to privilege in the core language
they don't seem to explain the rationale, either - that's the only instance of the word bytearray in the entire PEP, and bytes appears in only one other spot. π
!shhh
β silenced current channel for 6 minute(s).
!ban 724989356221399060 Take your terrible memes somewhere else
:incoming_envelope: :ok_hand: applied ban to @wise delta permanently.
!unsilence
β unsilenced current channel.
yikes
thought ela got mad at the string issue for a sec π
is not Python introspection slow? that pattern matching will use a lot of it, no?
also i may have misunderstood how this pep works
so imma go read it in full now
i don't think it should be much slower than just if/elif/else?
match number:
case 0:
print("Nothing")
case 1:
print("Just one")
case 2:
print("A couple")
case -1:
print("One less than nothing")
case 1-1j:
print("Good luck with that...")
like literal matching should be fast
afaict it literally translates to if/elif/else
so match x: case int: is if isinstance(x, int):
Yes I saw, its not too complicated to the interpreter
This looks highly useful
some instance type checking and direct attribute access
It's still a decent QoL improvement
@paper echo are you sure it works like that
with the types
saw match x: case int():
yes that will make the code more clean
I agree with the above opinion that the prefixed dot operator to enforce name resolution is a bit odd
More syntax to remember 
yeah i dont like it one bit
its completely out of left field from existing python syntax
I'd have gone the other way, I think... Rather than making name capturing be the default and adding special syntax for accessing variables, I'd have made accessing variables the default and added special syntax for capturing...
^^^^^^^^^^^
They could've done something interesting with a new operator like & to bind expressions instead of patching on the dot operator to do name resolution
I'd prefer a completely distinct operator for readability
though
I can see the rationale for the dot operator since it's being treated as a resolution in the current namespace
Meh, I guess I can only be averse to the semantics not the syntax
Syntax is bikeshedding
its not bikeshedding if the entire project is designing a bike shed
lol
the dot syntax is the programming equivalent of a norman door
This is the time to have opinions on the syntax; that's the entire purpose of a PEP.
Someone willing to help me fix a small problem on big project pm me
I'm trying to say that the dot operator as the operator to specify name res isn't as important as the fact it's doing name res to begin with
we donβt do dm-help and youβd better go to one of the help channels @weak lotus
I can see where they were going for but it feels incredibly inconsistent with the rest of python
right. as godlygeek said
If there was a more fleshed out resolution operator then I'd be more relaxed
But this is ad-hoc
It needs a lot of reconsideration imo
current ideas are ambitious but not quite pythonic
It's an interesting cross between guards and scheme's case analysis
I like the idea of making unary & or + do the name binding, so that a name without that unary operator applied to it unambiguously means a variable resolution.
I'd stick to & since that's an easy map to a reference in other languages
Immediately recognisable as you're indirectly mutating that value if you're familiar with other languages with pointers
it's actually used as a unary operator in Cython, though, so it would be somewhat ambiguous there...
that wouldn't be so bad, I think - it's currently a binary operator, it could be made unary as well, and you could read "@x" as "match and store at x"
There's usually more aversion to introducing a new operator than to repurposing an existing one.
anyone down to hop in a vc and help me fix an exception problem
I guess using an operator to indicate binding wouldn't play so nicely with class patterns, though. Instead of python match shape: case Point(x, y): ... case Rectangle(x0, y0, x1, y1, painted=True): ... you'd need python match shape: case Point(@x, @y): ... case Rectangle(@x0, @y0, @x1, @y1, painted=True): ...
After the walrus operator debacle, that's certainly evident. However, this is an entirely new behaviour that's hard to generalise to other operators
the walrus operator was a visual change to regular assignment which gave the reader a hint
retrofitting another operator may end up with more confusion because now you have two entirely different behaviours
personally, 2 different things doing 2 different things is better than 1 thing doing 2 different things depending on context
would it be weird to see the new operator on the RHS of an = for a keyword argument being bound? ```
case Rectangle($x0, $x1, $y0, $y1, painted=$is_painted)
Yes, better keep with the dot
bare in mind this is a discussion where the $ operator is for binding, not name resolution
true
but conflicts with sets
then again, Guido hates brackets 
though it should not matter, because you cannot unpack into a set, so I would guess you cannot match on it either
In [9]: {a} = [1]
File "<ipython-input-9-24859e2b15c3>", line 1
{a} = [1]
^
SyntaxError: cannot assign to set display
I think that's too ambiguous
It makes sense when you think about it but I can still see myself slipping up regularly
please no operator salad
sincerely,
salt
raku is raku, python is python
?? and ?. and := are fine, they serve a serious need
you mean <<+<< is not the perfect operator
if we need an operator to disambiguate referring to a name and capturing a name, I'd much rather see it on the capture (the new concept) instead of the reference (the existing concept)
can't wait until python adopts rakus custom operator system. def postcircumfix:< < > >(a, b):
looks like C++ π
int(i)matches any int and binds it to the namei.
blink
why make that the default behavior, instead of having people do i := int() ? That seems really strange to me...
hey guys
so what's this for? https://github.com/gvanrossum/patma
is this kind of "choice"?
wait what was wrong with just having default like every other language?
i mean if they're adding keywords...
int(i)matches any int and binds it to the namei.
@raven ridge tf
most languages with pattern matching use either _ or otherwise, which is just alias for True, or else
the argument there would be that they're already adding a wildcard, and that it makes sense to use the wildcard alone to indicate "anything else"
ah hmm
default is more common with imperative switches.
otherwise you're adding two different types of wildcards, one that's only usable at the top level and one that's usable inside a submatch.
default sounds like a way to do it tbh
would you get rid of _ then?
if there's a two-tuple and you want to get just the first value from it, this lets you use case (x, _) as the pattern.
having just spent the whole day using _ as wildcard in elm pattern matching, it works well
@raven ridge yeah i am not a fan at all of that, and im actually surprised this pep is being accepted with that stuff in it
the int(i) binding
i know its like how functional langs do it
but
this PEP isn't being accepted at all yet; it's just a proposal so far.
ah ok i thought it was further along
the problem here is that namespacing is hard
i get why they did the . thing
the PEP is starting the discussion, not ending it. it was just published today.
its just so weird
cool
you know what id settle for?
typing.Literal[BLACK]
with the extension that typing.Literal[BLACK, RED] is equal to typing.Unionp[typing.Literal[BLACK], typing.Literal[RED]]
v1 = 1
v2 = 2
match number:
case Literal[v1]:
but maybe that can get conflated with the destructuring
we GNU R now boys
oh no π¦
honestly, I still like
v1 = 1
v2 = 2
match number:
case {v1}:
im trying to think of a heinously convoluted R example off the top of my head but i cant rn
@flat gazelle how does that work with sets being a valid collection type?
I'm still working my way through this PEP - there's a lot to unpack here (pun intended). But one thing that strikes me is that it will be backwards incompatible for a class that doesn't have a __match_args__ to add one in the future, because it will change the meaning of Class(pattern) in existing case expressions...
are they? They are not valid targets for unpacking, but I guess they do make sense to be matchable. Did not think about that
i still cant believe all this is to avoid if/else
if I get it right, problem is to decide whether given x in case x should update x or be checked against x?
case x to assign x sounds pretty dumb
i agree. but what if it's parameterized
"i want to match such that the first element is equal to "ZZ" and the 2nd element is captured"
how do you express that?
ah fair
for that matter, "i want to match such that the first element is equal to "ZZ" and both elements are captured"
.something makes sense at this point
because == can be arbitrarily redefined by any object at any time
short and fine once you get it
lol
and i love R
i still cant believe all this is to avoid if/else
@paper echo It's not to avoid if/else, since (unlike aswitchin most languages), the performance characteristics are exactly the same as if/else. It's to provide pattern matching on arbitrarily complex subexpressions.
well
@raven ridge but how often is that desirable
compared to allowing isinstance to work on Protocol subclasses
we should be moving away from unqualified tuples and dicts
we have friggin dataclasses now
it works on classes, as well, not just unqualified tuples and dicts. this would be quite useful on dataclasses.
because at runtime you'd have to check every element of an iterable to determine that it's an Iterable[int]
which is obviously problematic if said iterable is infinite
it's not a matter of will or manpower
I see
this is why im saying extend isinstance to Protocol
or even this makes no sense they already workdataclasses for that matter
gotcha
yeah i just dont see how often you really need this kind of aggressive destructuring matching
its replacing "lines of code" with "syntax magic"
in a way that doesnt seem helpful
again, contrasting with the None-aware operators which have clear semantics and significant complexity reduction benefit
i would sooner adopt something like glom or toolz.get_in before this pattern matching
/rant
On a very high level it is similar to regular expressions, but instead of matching strings, it will be possible to match arbitrary Python objects.
I think that's a good framework to view the proposal in.
I think I would have wanted this more than never, but not terribly often.
the guards are probably the most useful part of it relative to plain if/else blocks, I think
at least, in terms of where it would be most useful in an average Python program...
because that gives you the ability to fall down into another case block even if you already partially matched in one, which tends to be a place where if / elif gets messy.
but then couldn't you make match/case just act syntactically like if/elif/else
match <expr>:
case <expr>:
case <expr>:
so its just if/elif with fallthrough
or hell give me a special keyword to manually fall through
there was an alternative proposal I heard kicking around, which may eventually see light as a different PEP, to augment existing unpacking methods to support a kind of structured unpacking of dictionaries and classes, instead. {"outer": {"inner": value}} = some_dict; print(value) or the like.
elif
For what it's worth, I would've preferred else as a catch-all statement like scheme
It'd be consistent with else's appearance everywhere in pythons compound statements
but my point above stands - as long as _ is a catch-all wildcard in a submatch, it would be inconsistent to not allow it as a catch-all wildcard in a top-level match, and if you already have that as a catch-all wildcard, adding a second one would just be syntactic sugar.
that is, as long as case (x, _) works, case _ should work as well, and as long as case _ works, there's no reason to add an else that's semantically equivalent to case _
I suppose
@raven ridge I like that version better, because it's an extension of existing syntax rather than something completely new that also forces a bunch of really difficult decisions like the ones we are discussing now
Someone knows how Can I automate some SSH tasks using python? (Usually I open an SSH terminal, go to some paths, execute some scripts and get some informations on the screen to excel.. etc) Could I do it using python? Someone knows what I need to learn to do that?
Someone knows how Can I automate some SSH tasks using python? (Usually I open an SSH terminal, go to some paths, execute some scripts and get some informations on the screen to excel.. etc) Could I do it using python? Someone knows what I need to learn to do that?
@supple heath https://medium.com/@simon.hawe/save-time-by-automating-ssh-and-scp-tasks-with-python-e149de606c7b and I think that for working with Excel you'd want to use openpyxl
thanks
An interactive python shell can also be handy, since you can add functions on the fly and stuff
But maybe you really want an orchestration tool for this task.
Well, there are orchestration tools written in Python as well.
I really need to do a place.. (language - Python maybe) to do a lot of things.. Automate my repeated tasks.. Execute scripts, read screen, open Jira tickets, open excel, send e-mail.. etc
but I'm looking about Ansible or Python.. Idk what is better and what can I do
I know that I could do all this with python..
but someone told me about Ansible
this isn't really the right channel. #tools-and-devops would likely be better.
ohh.. sorry @void sonnet
hehe. no worries.
@raven ridge what version do u have as python3?
that definitely belongs in an off-topic channel. this machine is running Ubuntu 18.04, so 3.6.
Trust me itβll be on topic
When youβre free can you try and write a c lib that uses _PyLong_FromByteArray? (or As)
As shown here
I canβt get CLion to pick it up on my Mac, even tho Python.h includes that header file
Itβs not documented, but I donβt get why itβs not available, since PyAPI_FUNC should export it, and itβs definitely in the header file
@raven ridge
seems to work for me. I just quickly did:```c
#define PY_SSIZE_T_CLEAN
#include <Python.h>
int main()
{
void as_byte_array = (void)&_PyLong_AsByteArray;
return 0;
}
Oh hmm
Ok maybe I just need to update the documentation and add a macro so it doesnβt have an underscore then
I believe having an underscore indicates it's part of Python's private API, not its public API.
Iβm making a PR to make it public tho
might be worth a search on the bugtracker to see if there's any comments about why.
I made a post to the capi-sig mailing list, they said it was ok π€·ββοΈ
(Well one guy did)
anyone know a dynamic method of adding all the lists to the itertools.products() without having to type it out; the dynamic part is due to preseq being variable in the number of lists it has
itertools.product(*preseq)
@unkempt summit like this?
Oh u guys moved here lol
was this a followup from a help channel?
General channel lol
oh
i didnt move anywhere
!e ```python
from itertools import product
preseq = [(1, -1), (2, -2), (3, -3), (4, -4)]
postseq = list(product(*preseq))
print(postseq)
@paper echo :white_check_mark: Your eval job has completed with return code 0.
[(1, 2, 3, 4), (1, 2, 3, -4), (1, 2, -3, 4), (1, 2, -3, -4), (1, -2, 3, 4), (1, -2, 3, -4), (1, -2, -3, 4), (1, -2, -3, -4), (-1, 2, 3, 4), (-1, 2, 3, -4), (-1, 2, -3, 4), (-1, 2, -3, -4), (-1, -2, 3, 4), (-1, -2, 3, -4), (-1, -2, -3, 4), (-1, -2, -3, -4)]
@red solar oh sorry dood, didn't see your message
Itβs ok salt answered it well
@paper echo @red solar thanks i appreciate the help
what exactly does the asterisk mean?
i know when you print a list e.g. print(*list), it will print out the strings rather than a list of strings on one line
ah, okay I get it
@unkempt summit it "unpacks" the iterable, passing each element into a separate argument in the function
This stuff makes python so weird and I don't know if I love or hate that... Even if there are great use cases
[*range(10)], for example, would give you a List of ints from 0 to 9. You also see it in functions.
for argument in largs:
print('I am processing an argument')``` Where you can call `example('apple')` or `example('apple', 'pear')` @unkempt summit
Then there's keyword argument double stars, where you define functions like
return kwargs``` If you feed it `example(a=apple', b='pears')` it returns `{'a':'apple', 'b':'pears}`
I'd like to create a class which acts like an instance for itself directly. Let's say I want to subclass list like this:
class LineColor(list):
def __getitem__(self, index):
try:
return super().__getitem__(index)
except IndexError:
return (255, 255, 255)
LineColor[2] # This should give (255, 255, 255)
Obviously, this won't work and will raise TypeError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
But is it possible to do it?
Can you have a class that you can use directly, just like an instance of it?
Note: I know it's not a great idea to do it, but I just wonder if it's possible, and if so, how?
and you can have positional arguments in your defs, too, example(arg1, arg2, *largs) but the starred stuff has to come after
and you can feed starred and double starred stuff into other function calls, too. example(*largs) example(**kwargs)
@radiant scroll First option that I can think of is making it implicitly a singleton object e.g.
from collections import UserList
class _LineColor(UserList):
def __getitem__(self, index):
# ...
LineColor = _LineColor(...)
you could use a custom metaclass
yeah, that would be an option, but I was thinking to do this directly with the class, without even making an instance of it
and override the __getitem__ of the type
how can I do that gm?
I heard about metaclasses before, but I never got to use them
class GetitemMeta(type):
def __getitem__(self, value):
return 1
class Concrete(metaclass=GetitemMeta):
pass
Concrete[0]
you need to do some other stuff though, to make it work with your class
which on the whole would make it kinda not worth it if you're not already familiar with metaclasses
like I think a singleton or some other abstraction would work much better
yeah, in practice certainly, but this is more for just my curiosity
I'd just like to know how to do this, as I said in the first message I don't intend to use this right now, but I'd like to know how it works
so, if you have the time, what other stuff would I need?
but I get it if you don't
you can also use __class_getitem__ for that particular example instead of a metaclass
In [280]: class LineColor:
...: def __class_getitem__(self, key):
...: return 255, 255, 255
...:
...:
In [281]: LineColor['hi']
Out[281]: (255, 255, 255)
maybe, i'm not sure exactly what you want --- if you want exact list behavior you could just subclass list
yeah but you can't use it to define custom generics π’
Dependent types > generics, change my mind
to be fair, i've use metaclass getitem more than class_getitem
because i've used it once
apparently there are a lot of issues with dependent types
lol
what did you use it for? curious
Why are you both salty...
i could see class getitem being useful for defining some kind of fun shared caching semantics
because i wanted the class logic to be mostly related to interval mathematics -- all the other stuff i put in a metaclass
interesting
i've thought about undoing it though
i like this alternate constructor because you can easily subclass it to obtain things like np.arange
interesting, well, thanks a lot guys. I'll have to take a deeper look into metaclasses, they seem very interesting
Just question, appending to @radiant scroll s one, what you use metaclases for?
Can advanced Python be used to program a motherboard circuit?
@unkempt rock metaclasses are used to make classes
As you can see here, Par is of type type, because it is an instance of class type. This makes type a metaclass
Correct me if I am wrong anyone
yikes
there is spaces
isinstance()Β is one of the most called functions in large scale Python code-bases (by static call count). In particular, when analyzing some multi-million line production code base, it was discovered thatΒ isinstance()Β is the second most called builtin function (afterΒ len()). Even taking into account builtin classes, it is still in the top ten. Most of such calls are followed by specific attribute access.
From PEP622
That's interesting
isinstance is used that much because it is dynamically typed?
That sounds unpythonic, especially cause it points it it's followed by attribute access
Anyone ever heard of duck typing? Geez
I think the main issue is that we don't have operation overloading in python, so you have to check the argument type to choose how you are going to process it
yes PEP 622 is some weird shit
it was felt that it might be better to acquire some real-world data on how the
matchstatement will be used in practice before moving forward with some of these proposals
literally no one would use it
How so?
They seem confident people would use it, especially if what they say about isinstance is true
in actual business logic, nested structures are very common
this is very convenient for dealing with them
I wonder if it's also simply because people want to present a unified interface capable of accepting multiple datatypes. The real work has to be delegated separately based on the datatype received.
I'd imagine that as the biggest reason why such a thing would happen, but I'll openly admit I'm still honestly shocked at that finding
Like, I feel like there's so many more candidates that should have been more common, at least print and open for example
print is almost never used in real applications, logging is done differently and you generally only open one or two files
it will not see as much use as it does in haskell/elm/*ML because you do not use it to make recursive functions, but all the other applications still hold. Java is also getting a similar system, despite java having a different way to do this with inheritance trees (those are also a thing in python, but are a bad idea to use as much as in java)
"even taking into account builtin classes, it is still in the top 10" is an interesting clause there. Python has only ~70 builtin functions and classes per the table at https://docs.python.org/3/library/functions.html#built-in-functions - and isinstance being used more than 85% of those doesn't surprise me in the least; many of them are very rarely used .
It shouldn't be shocking that isinstance is used more commonly than divmod, issubclass, eval, hex, ord, chr, etc etc. I'd go so far as to say that many of those have no business being in the builtin namespace, if it wasn't for backwards compatibility.
hmm, i never really use ord, chr -- except for aoc
so is this switch case with pattern matching?
tes
Itβs so hard to find an idea for a library that implements something that was not done before
I usually just make an api for a website and call it a day
like, consider urbandictionary
I have an idea for a library though. A game library that spams decorators everywhere and somehow makes it work
I'm looking forward to pep 622!
I hope it passes. I really yearn for switch/case functionality.
I also have a lot of isinstance calls in my framework since I allow users to wrap Discord objects in Django model objects and use them mostly interchangeably
only that if wrapped they have a couple more DB related features
So with match I could just group behavior easily and it's much more pleasant to read
I like Rust's match operator
A description
Oh, that looks like kotlin's when statement
It'd be interesting to see something like this in Python
The PEP seems very switch-centric though
Yeah
The cool thing about Rust's match is that you always have to handle all cases
Prevents a whole bunch of errors
Yeah, same in Kotlin, but I don't think python is rigid enough for that
If you don't handle all cases it won't even compile
yeah it's not
I've taken quite a liking to using Rust together with Python recently
If you want to check it out: https://github.com/PyO3/pyo3
ye o3 is pretty good
Would we have case class then? Like in Scala?
I'd expect it to be something like
match type(obj):
case str:
...
case int:
...
Take this with a grain of salt though.
case classes are probably not really suited to python. Python is not very suited for complex inheritance
composition over inheritance
I feel like this is gonna be the best area to ask seeing that we havent got the native lib channel yert
so
How do we handle Futures or async in general in C and C++ which is then handled by python
@cloud crypt there seems to be a lot more for social science in R than python... so - if you wanted something to develop then something along that line might use useful π
I can't understand the benefits of R
I have to use it for my psychology course and it's horrendous
@radiant fulcrum do you mean you're spawning threads in c/c++ and you want to get the result of each thread in python?
composition over inheritance is the worst mantra ever
i think inheritance is most helpful
Sure
But unless you specifically need what inheritance gives you over composition, iβd still always go composition
the only composition that matters:
class MyClass(Parent, OtherParent): # "composition"
ππ
The issue is that inheritance can be abused in a way that composition canβt
And the easiest way to avoid that is composition over inheritance
@subtle pike it was designed to work with data, there are lots of statisticians that work with it, there are many libraries existing for working with stats, it has a fantastic plotting library, etc
composition can be abused, because people could just use a simpler inheritance
I folder with a list of .py files - another .py file outside the folder creates a python file that inherits from every single class in that folder, and then it imports that python file and uses that - can you abuse composition that badly? @deft pagoda
@magic python the plotting library is featureful but is pretty easily replaced with python libs. The data science aspect is accurate, it does have a lot of built-in vector operations but python + scipy/pandas also achieves this. All I see is that with R you have a language that's a nightmare to debug and use without the documentation/community of python
Every academic I have ever spoken to about R agrees it's a language of chaos
the syntax is bad and the language is far from convenient
i think R is one of the most liked languages of all languages, though I know nothing about R -- and this is definitely off-topic,
i have never heard that
never mind, it's middle of the road https://insights.stackoverflow.com/survey/2020#technology-most-loved-dreaded-and-wanted-languages-loved
idk how i feel about go being so high up
not really sure if this is a question for this channel or not, but is there a way to see if the python file being run is in a zip or not?
meaning, like downloads -> ZIP -> script.py
that's not a question particularly for this channel, but i don't think that's possible since the file is unzipped before run
you can try asking in a help channel, see #βο½how-to-get-help, but no promises on getting an answer
ah alright
@deft pagoda that shouldnβt be how you use composition. Imo it should be something more like:
class Q(composer):
pass
Q.attach( factory_part1 )
Q.attach( factory_part2 )
etc.
And have specialised behaviour that deals with composition in a better way than just inheriting methods
Obviously, the downside is that the development team and anyone reading your code will have to be made aware of the (sort of different?) paradigm you are using
i don't know what you're talking about
Nevermind! I just realised you were joking lol
@tawdry gulch elaborate a bit more on that?
not seen it before
(i think gdude may have tried to explain it to me once a while back)
from https://www.mail-archive.com/python-dev@python.org/msg108627.html
def http_error(status):
match status:
case 400:
return "Bad request"
case 401:
return "Unauthorized"
case 403:
return "Forbidden"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something else"
isn't case _: kinda ugly? why not just else:?
or at least case ...:
i don't mind case _:, but else: does also make sense to me
https://www.mail-archive.com/python-dev@python.org/msg108633.html
Iβm with others who think that
else:would be a better choice thancase _:.
Given my background in i18n (see the flufl.i18n library, etc.), my red flags
go up when I see bare underscores being given syntactic meaning.
nice :p
nice to see other people fighting for it so i don't have to lol
i just hope this doesnt get rushed through
i like this version
case Point as (x, y):
print(f"Got a point with x={x}, y={y}")
i just realized. pylint is going to have a field day with all those returns. #ThereCanBeOnlyOne π
though, i'm confident they'd get it straightened out fairly quick after it goes live (if).
That really makes clear the distinction of variable lookup and variable binding. With Point(x, 0), x looks like a lookup
That would be better than add an operator for each binding, no?
I liked the suggestion of case Point with (x, y): better than case Point as (x, y): - we want to match a point with some properties.
Anyone here know Flask? I'm trying to get it to route to a /tools page, but it keeps redirecting to /tools/, which messes up future redirects...
Just wondering if there's a rule against /tools pages or something, or if it's likely to be a bug in my code that I just haven't been able to find yet.
(Of course, right after I post, I figured it out. It's not a flask problem, it's a livereload problem - so I just stopped using it. It seems to have caused more issues than the one problem it fixes somewhat)
@final mica in the future keep in mind that this is not a help channel. Please read the channel description.
https://paste.pythondiscord.com/vawezikipo.py i hav apsted my code here?
can u guyz hav a look here @void sonnet
If you're looking for help with code a help channel is probably best. See #βο½how-to-get-help
Also don't ping random people
@minor sinew Sorry for the latest response, no its not quite what i ment
Currently Im trying to work with Futures in both Rust and Python
But binding / linking would be rather hard without understanding how the underlying Cpython handles futures itself with asyncio
thats sorta what i was getting at
.fool
wow 3 new peps in the span of 4 days
Greetings
@unkempt rock care to explain that?
what are the new peps?
you can find them listed #mailing-lists here
Internally, what makes a while loop different, compared to a recursive function ?
a recursive function adds to the call stack, and you can only go so far before you reach a limit
Essentially recursive functions have to remember where they were called and what the values were in that scope at the time. Where as a while loop literally just keeps on going down a straight path (albeit one that loops back to a certain point)
Call stack is a funky thing to understand at first
does running socket library and selenium cause problems?
like running one after the another in the same program.
not that i've seen
i would imagine you're doing something weird with threading to cause that maybe
can you show your code
No, I a not using threading. I have a different python program for port scanner, and selenium starts executing after the port scanning is complete. I have this complete explained in #help-falafel
@hollow crane here is the code. Please @ me if you reply. Thanks
doesn't the case statement already exist as a dict mapping?
match thing:
case a:
return a_stuff
case b:
return b_stuff
things = {a: a_stuff, a: b_stuff}
return things[thing]
match/case should allow for different types of patterns iirc so it's a bit more flexible
https://paste.pythondiscord.com/madozucoqa.py
@torn plank anyone is more than welcome to review it thanks.
Dict requires the matches to be hashable, no?
yeah
any python project website like jetbrains academy
Does python do any recursive call optimizations
Nope
So favour iteration over recursion if both are equivalent, the iteration will probably perform better.
does pypy have tail call optimization?
>>>> def fun(a):
.... if a:
.... return fun(a - 1)
.... else:
.... return 9
....
>>>> fun(1000000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in fun
File "<stdin>", line 3, in fun
File "<stdin>", line 3, in fun
[Previous line repeated 2334 more times]
File "<stdin>", line 2, in fun
RecursionError: maximum recursion depth exceeded
```seems no
Thatβs a rip
π¦
https://paste.ofcode.org/zsqnBH2pyG2Hz3menbmm9h
Can anyone help me figure out why any number below 100 or above 500 in line 8 does not return properly instead is just spammss the numberr
for example if its 501 then i get
501
501
501
501
and so on ,also this is not the whole code, i'm template matching from my screen.
@deep willow This is not a help channel, please read the channel description. If you want to get help with a specific question, check out #βο½how-to-get-help.
oh srry i read it just didnt understand it i do now thanks
There's a suggestion to have set.add return a bool depending on certain things, and I said that that change would have to be part of a larger discussion about what mutator methods should return if they don't return None
I'd want to see them return self
If someone has been writing code that uses what mutator methods return up to this point, they deserve for that code to break anyway.
swear there's some other datatype where adding an element returns a bool
I remember in C, a lot of data structure functions return 1 if it worked and 0 if it didn't, since you don't get exception handling in C.
In fact I think accessor methods work the same way, and you'd give them a pointer of where you want it to put the accessed item.
oh C
lol nah return -1 and set errno, surely?
but .i was more talking about in python
maybe i'm imagining things, and i was just coercing None to False
Not a fan of that with python's design, and it would require changes in a lot of places along with confusing for non 1st party libs that do it like it's now
If someone commits their venv folder to their git repo (I didn't do it), isn't the storage footprint of the repo permanently significantly larger unless they delete that commit?
Yes unless a commit undoes (not the same as rewriting history and deleting the commit) it and a shallow clone is done
#tools-and-devops feels more appropriate for this
I suppose. That was my only question on that.
Any good resources to get started to cython apart from documentation
It feels like python if flowing more and more toward something like java
the push with classifying a lot of stuff (dataclasses, enums), type hinting, and now the case/switch-ish PEP, and probably some things I forgot
Do you guys agree? What do you think about it?
imo dataclasses are quite the opposite of Java classes given the fact that they're boilerplate killers
right, but in the sense that it's something that you earlier would've done with a more primitive type or a namedtuple
Fair point
Well at least to me, dataclasses remind me more of Haskell's record syntax
I love dataclasses, don't get me wrong, but I think namedtuples are peak pythonic
(I almost never use namedtuples though... lol)
This too is pretty awesome
> Namedtuples and dataclasses will have auto-generated __match_args__.
> For dataclasses the order of attributes in the generated __match_args__ will be the same as the order of corresponding arguments in the generated __init__() method. This includes the situations where attributes are inherited from a superclass.
feels good man
I've just resumed reading the PEP again and then I see this
https://www.python.org/dev/peps/pep-0622/#sealed-classes-as-algebraic-data-types
If anything dataclasses are like java records I think
can someone help me out in #help-pear
@unkempt rock Please don't advertise your channel/question elsewhere, just wait patiently, if someone can and wants to help they will
any suggestions for extracting data in large scale from PDF ?
@brave badger that looks gnarly
i always end up with a type alias like T = Union[A, B, C, ...] at the bottom of a scary looking types.py file
@red solar dataclasses are a crippled version of attrs classes
@cobalt glen This is not a help channel, please read the channel description. Check out #βο½how-to-get-help
Hi, I am stuck in some python code, I am doing this just for fun and to learn about tensor flow, Keras and image classification, But I can get an improvement on my accuracy....maybe you can give a tip or an idea here is my code https://paste.pythondiscord.com/obixuyixuf.py
@lethal prism I don't know anything about TensorFlow, but one tip for convenience and readability is to bunch multiple import statements that grab from the same library into one statement.
For instance, I notice that you are importing a lot of things from keras.layers. You could rewrite all of those import statements into one with from keras.layers import Sequential, Conv2D, MaxPooling2D and so on.
How to send notification on Android using PYTHON?
@lethal prism I don't know anything about TensorFlow, but one tip for convenience and readability is to bunch multiple
importstatements that grab from the same library into one statement.
@unkempt rock Thank you for this
NP
Maybe both of you should go to a help channel -- see #βο½how-to-get-help
4
No. PyPy follows the Python language design, including the built-in debugger features. This prevents tail calls, as summarized by Guido van Rossum in two blog posts. Moreover, neither the JIT nor Stackless change anything to that.
How can I make logging.exception() log only the first 2 frames of the traceback?
You may need to use the traceback module to limit it
And explicitly pass the exc_info tuple with the modified traceback
I've not tried that but I feel like the traceback module would have something relevant for you
Is it possible to change de default logger class? I would like to overload exception
You could just monkeypatch it I believe
I think that is enough
does web-assembly means front-end web app can be written in Python in future?
i don't see how wasm would help with writing a front-end web app in Python?
You need to convert a Python interpreter to webassembly first, and then you can use it to run arbitrary Python code, from what I understand.
you can't just write a python interpreter in JS?
technically, sure. Practically, wouldn't be a great use of time.
i'm sure someone's written a c to js transpiler
now i wanna try and find it and try it on the cpython repo
couldn't say, I avoid JS like the plague π
lmao dog keeps getting deleted (try in off topic channels)
same (except maybe typescript)
you can't just write a python interpreter in JS?
@red solar https://github.com/beeware/batavia
What do you mean by atomic?
I am not familiar with the concept but if I understood correctly, GIL would prevent race conditions for all python level objects (at least in cpython) so there wont ve any need for that types.
1, isn't GIL an implementation detail rather than a language feature? and 2, what about items in shared memory, accessed by multiple processes?
GIL is in an implementation detail (it is why I specified at least in cpython, but other implementations should be responsible for preventing such race conditions regarding all objects).
I am not familiar with the shared memory implementation, so no answer to that.
is there any reason you know of why cpython wouldn't be open to the suggestion of an atomic library?
No, I am not familiar with the concept
ok i'll make a suggestion to python-ideas once i have a complete library
Uhm
I think python operations are already atomic
Most of the builtin methods, translate to a single operation on a dis.dis breakdown. So such a library would be redundant at best.
And if it's a custom operation you are doing, then you're already ideally using locks as usual
These statements are built on the premise that I understood atomic correctly, which may or may not be true π
Most of the builtin methods, translate to a single operation on a dis.dis breakdown. So such a library would be redundant at best.
@visual shadow being a single opcode on the Python level doesn't mean that they're atomic on a processor level
what's wrong with just
with lock:
# do thing
@red solar ?
it's a lock...
lock has additional overhead, and also not sure how you'd put a lock in shared memory?
oh. shared memory? like IPC shared memory?
yeah
each OS has their own interprocess synchronization primitives

