#internals-and-peps
1 messages ยท Page 68 of 1
python```
class foo:
x, y: int
x, y is not unpacking, that is an expression of a two element tuple of x and y
if you mean annotating multiple variables at once, like go and nim allow, that would probably be somewhat useful
most languages have something similar for variable declaration
well, in python you do not need variable declarations, so it is not that useful
I think the idea of declaring variables without giving them a value is just kind of weird...
It's only useful in stuff like this
int x;
if (foo < bar)
x = spam;
else
x = ham;
but this is easily replaced with a conditional expression
int x = foo < bar ? spam : ham;
You can do this:
a: int
b: int
a, b = myfunc()
if it helps your IDE or some other use case where it'd be useful
https://www.python.org/dev/peps/pep-0526/#global-and-local-variable-annotations says to define them before unpacking but if there are alot of variables it end up looking like boilerplate, also if i have the type already made somewhere id have to remake the structure a: int b: int a, b = t
sometimes I'll do annotations like that to get PyCharm to autocomplete something for me or confirm that something exists but then probably remove them before I commit the code
so if i have something like color = Tuple[int, int, int, int] ... r, g, b, a: color = something_i_want_to_know_is_a_color
I don't think thats valid syntax
yes
or is it?
its not
what is the goal you are trying to achieve?
if you want to type check one of them you can annotate them temporarily
I don't find myself in situations where I'd need the annotation to be there at runtime usually
I would agree that
r: int
g: int
b: int
a: int
r, g, b, a = ...
is awful
but in that case if i had 100 places where i did that, id have to change them all by hand if i wanted to swap the ints for floats for example. but in my example id just have to change one line, the color type definition
normally you would just annotate the return type of the function that is giving you the tuple that is being unpacked
or annotate the tuple itself
it basically has the same problem as hardcoding values
so, for example:
return_value: t.Tuple[int, int, int] = some_func()
a, b, c = return_value
but this is all assuming that you cannot annotate some_func for some reason
again I think it depends on the end goal, if you for example want mypy or pycharm to know their types then this should be 100% sufficient
if it's just for the readers convenience, you don't need to use the annotation syntax, you can just put a comment
you make good points
I haven't used mypy much but afaik if it complains about the inability to infer the return type of a function call from some library, this should be enough to make that go away
and then mypy can do its thing with the assumption that those types are annotated correctly
there are cases where this isn't sufficient but i guess Special cases aren't special enough to break the rules
mm yea
I've also come across situations where I would have found it convenient to do
a: int, b: int = something
but I haven't come across a situation where I wouldn't be able to refactor the code so that I can express the same using valid syntax
if you're actually unpacking, you probably don't need the type hints
[if some_func has annotations that should be enough, for example]
if not, you can declare a: int; b: int; c: int on a preceding line
something: Tuple[int, int]
a, b = something
depending on the situation this could make sense too
@cloud crypt sry
I mean, personally I would just declare types on a seperate line
hi everyone, sorry for interrupting, but i have a code that im trying to figure out and i need some help...
Hello @empty ruin, this channel is for discussing the Python programming language itself, from a higher-level perspective. For help questions, you can claim a help channel or ask your question in one of the topical channels (if one fits). See #โ๏ฝhow-to-get-help for more info on how to claim a help channel for your question.
!tempmute 742079691569234050 14d You're not funny
:ok_hand: applied mute to @unkempt rock until 2020-09-07 22:16 (13 days and 23 hours).
quick question about naming convensions, if I have the force of gravity (Fsubg) would the shorthand variable be Fg (because of the subscript) or f_g (following pep)
I want to know that question too. To expand on it, how bad on the scale from 1 to 10 would be to use
Fแต
? ๐
see that looks like F^g to me
which is weird
ah yes the force of 9
gravity_in_newtons ๐
it's the 9th coordinate of the multidimensional force covector
^^
idk I just find it weird how a massive part of python's use is the scientific community yet there aren't any standards put in place for it
I mean, there is, it's PEP8 and it says not to use unicode in identifiers if I'm not mistaken
Working on scientific systems doesn't mean you don't use qwerty :P
I never said anything about unicode lol
Fะถ
I was referring to the symbols used above, which I guess you didn't propose
But still, we have snake case for variables, pascal case for variables etc, imo we're fine as is
I don't really get why anyone would want that.
If you're unfamiliar with latin script, it's pretty challenging to write python code.
Especially if you're using third-party libraries that have English identifiers and English docs.
My native language uses cyrillic script, and I'm not going to name anything using it even at gunpoint
But maybe it's too close to Latin script, and people from other cultures have a different opinion.
but then you can make your names ัะธiัั
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
True
You are not allowed to use that command here. Please use the #bot-commands channel instead.
the eval uses python2 ????
<rant> Unicode support actually made me spend a minute or two debugging my code... Cyrillic and Latin scripts share a lot of character, and I accidentally used a Cyrillic ั instead of Latin c (conveniently, they are located in the same place on the keyboard). And I couldn't figure out why it was giving me AttributeError </rant>
I've seen at least one person with the same problem in the help channels.
I don't really get why linters don't complain about that.
do they complain about non-ascii in general?
An ide would easily catch that
also I find it weird how py has all these conventions but ide's don't enforce all of them
like in cpp if I have:
return Fg/a; ``` it autocorrects to:
```cpp
return Fg / a;```
Press the auto-format hotkey and it will.
is autopep8 installed by default?
depends which IDE, pycharm definitely comes with an autoformatter by default
black is arguably better than autopep8. It guarantees that it never changes your AST, and it has the advantage of being extremely consistent across everyone's codebase who uses it
and the minor disadvantage of being an absolutely atrocious style that no one seems to actually like, but that is technically pep-8 compliant.
wait, autopep8 changes the AST ?
that's outrageous if true
(also fwiw I much prefer black's formatting than like yapf)
I know I've seen weird things from autopep8 in the past, but I haven't used it in a long time and can't speak to the current state of it. But I know that black re-parses before and after and makes sure the AST matches before committing anything
Ironically, if you automatically format all your code to comply with PEP 8, you automatically violate PEP8.
because of this section
- When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
well, yes and no
no (sane) autoformatter will rename variables or methods
and those are the place where "foolish consistency" tends to come up.
In particular: do not break backwards compatibility
is talking specifically about that case.
Wait what's so bad about black's pep8 style?
it's not good for large literals, where you might want to add comments in the middle of a long list, or space elements onto separate lines even if they'll fit on one line.
there are problems with pragma comments: black likes to move things around.
from the bits I've seen here and from modules I've looked through, the line splitting isn't all that great
Ah
I like to run things through black. Then go through and change a few things for readability/it not looking horrible
Apart from, https://realpython.com/python-memory-management/ and https://www.youtube.com/watch?v=URNdRl97q_0, are there any more good resources on how python's memory management works?
Get ready for a deep dive into the internals of Python to understand how it handles memory management. By the end of this article, youโll know more about low-level computing, understand how Python abstracts lower-level operations, and find out about Pythonโs internal memory ma...
Nina Zakharenko
https://2018.northbaypython.org/schedule/presentation/19/
As a new Python developer, trying to understand how memory management works in python can feel like a daunting task.
The documentation immediately jumps into difficult to follow concepts, especially...
@unkempt rock those will probably cover everything. do you have specific questions?
Oh, I see. No, I just wanted to see if there were more resources on memory management cause I found it interesting
there's some very detailed stuff, if you want...
"Speaker: Pablo Galindo Salgado
One of the reasons why programming in Python is very straightforward and simple is that we do not have to worry about the lifetime of our objects. That is, once it ceases to be necessary, a variable disappears from the memory ""magically"". The...
they're pretty dense. Expect to need to watch/read it repeatedly, haha
hey babes
i'm not a babe, but what's up?
Hey there goku
It's impressive what you can get away with in python
Not sure you can really class a decorator as something you "get away with"
It was an example for class decorators, but I still find functions within functions calling functions that was an input strange
every major language supports it by now, it's harder to find languages that don't support it actually
Including non-object oriented ones?
yes
I'm curious, how useful have decorators been to people in real life applications in their day job? Life safer or just a convenience to reduce some lines fo code?
functional programming is pretty much based around the idea of having first class functions
I was curious about the uses of decorators in normal applications
It's not a class decorator though...
It's a function decorator?
Decorators do provide some ease to some degree. Never really seen a library with a nice API that doesn't have decorators.
I've used them for discord.py. That's it
In your code it's a decorator function, decorating a function
@brave badger that didn't implement decorators for the user of the API to use?
or which didn't use at least one decorator internally?
Both can apply in this case
ah
What do you mean internally?
the code in the library has decorators
^ that
I'm working on a library and I use different decorators a lot internally
Plenty of code is going to use decorators internally
I've been using them internally to check that the user doesn't screw something up
Writing them for internal, non-user-facing code often helps the maintainers of the library
@property @staticmethod @classmethod
@property is the one I use most extensively
makes the API a lot more elegant
I also found a library on pypi called cached property
it's similar to @property in that it gives you attribute-like access
but the first time you access it, it does however much computation is needed, and caches the result for all subsequent accesses
That exists in the stdlib now
Yeah
nice
Since 3.8
I'm at the point now were I'm just learning all the advanced features that I haven't needed yet. This discord is a lot of help ๐
not my decision though
for my job I write programs that take a long time to run, and for the most part I run them on one of the servers owned by the uni
on the one that has 200 cores, they won't install 3.7
it only has 3.6
I'm very upset about that.
What possible logic is there for taht
Effort
"3.6 is still supported"
Huh, so functools.lru_cache is pretty efficient when used with expensive pure functions
It's not really effort to install multiple python versions on a linux box
I dunno, the computers have tens of thousands of dollars worth of hardware
so they're slow to make anything available on them
Is there any random thing in python that you think people should learn, but most programmers don't know about?
a lot of people don't learn about sets
Various PEPs and stdlib stuff
Sets are amazing
and there are lots of great 3rd party packages that are effectively part of the stdlib for me now
such as attrs
Actually, I'm not sure if many people know you can call functions from dicts
I use generators in pretty much everything so from my perspective they're not underrated
but I guess a lot of people with extensive backgrounds in not-Python don't use them?
@unkempt rock yep it's a nice way to "dispatch" based on behavior. using dicts to replace a switch/case statement is a nice trick too
Actually, I'm not sure if many people know you can call functions from dicts
The problem with doing that is it get's unreadable fast
how often do you actually need a mapping of functions though
I've never actually had a use case for dicts of functions
Not sure if generators are a Python-only thing but I'm sure that some form of a lazy iteration protocol exists for most languages
but it's cool that you can do it, I guess
such as attr
Just use dataclasses
it's also a good way to illustrate that functions are objects.
ops = {
'+': lambda a, b: a + b,
.
.
}
op[input("Operation to use (+ - * /) ")](*map(int, input("a b").split()))
@safe hedge attrs is supported < 3.7 and has a lot of nice features that dataclasses lack. you can also integrate attrs with marshmallow now (using the desert library) which is hugely useful to me
@brave badger do ruby and perl have lazy iterator things?
salt I usually use them in most of my scripts to call functions from cmd
@unkempt rock you should hang out in #esoteric-python
obviously use dataclasses if you like dataclasses, but i will continue to advocate for attrs in most contexts
def run_function(self, line):
if line[self.pos] in self.function_list.keys():
self.function_list[line[self.pos]](line)```
@signal tide i use Click for that ๐
That place scares me
@paper echo I use dataclasses a lot; what are attrs?
There's no way they manually obfuscate python code there, do they?
@boreal umbra dataclasses but super-powered and they support __slots__: https://attrs.org
i have import attr in pretty much every nontrivial python program i write now
i use Click for that ๐
ya that would do it
I mean, if it's more super-powered than dataclasses, isn't that just classes?
I see
I'm just generally against the idea of adding extra dependencies to my projects
sure, thats why dataclasses were added
will this free me from having to use the same tuple over and over and over again for __eq__, __hash__, etc?
i dont mind a handful of well-vetted dependencies
@brave badger do ruby and perl have lazy iterator things?
@paper echo Not really sure, but there might be.
Anyone ever write python code for speed
One reason I still use argparse over click
the only langs i know with lazy iterators are rust, python, and i think haskell has them
yeah haskell is big on lazy iterators
@boreal umbra somewhat, you have to do a bit of extra work but less so than if you didnt use attrs
@attr.s(slots=True)
class BusinessLocation:
""" A business with a single, specific location. """
name: str = attr.ib()
""" Business primary or common name (not necessarily legal name). """
legal_name: Optional[str] = attr.ib(default=None)
""" Business legal name, if different from the primary name. """
other_names: List[str] = attr.ib(factory=list)
""" Other business names. """
structured_address: Optional[UsaAddress] = attr.ib(default=None)
""" Business address, as a structured datum. """
text_address: Optional[str] = attr.ib(default=None)
""" Business address, as free-form text. """
id: Optional[Union[str, int]] = attr.ib(default=None)
""" Unique business identifier """
def all_names(self) -> List[str]:
names = [self.name]
if self.legal_name:
names.append(self.legal_name)
names.extend(self.other_names)
return names
def has_address(self) -> bool:
""" Check if either structured_address or text_address is available """
return bool(self.structured_address) or bool(self.text_address)
Anyone ever write python code for speed
@hidden pewter Python is pretty much all I write in, so it's always faster than writing in other languages for me
imagine all the horrible boilerplate youd have to write to make that class work otherwise
duplicating all the names three times to support slots
not to mention the massive useless __init__ definition
Ah, the annotations for the class methods remind me of a question. When should you use annotations? Is it appropriate to use them in every function?
afaik cons lists can be used in place of iterators in Haskell right?
One of the great foils of writing code is you should probably document it in a way that makes it easier for others to use. However, trying to maintain a set of documentation apart from your codebase is tedious and very manual and prone to mistakes.
Well, what if I told you th...
@unkempt rock I use them for everything that I expect other people will use
class BusinessLocation:
__slots__ = ('id',)
id: Optional[Union[str, int]]
def __init__(self, id: Optional[Union[str, int]]):
self.id = id
its like 4:1 LoC reduction
valid arguments could be made that this isn't necessary
@boreal umbra Oh, so it's for readability? Does it optimize the code in any way?
nope, doesn't optimize at all
I see
@unkempt rock in my opinion you should use them whenever and wherever it makes sense to do so. the python runtime ignores them, but you can use static type checkers to check the types of your code. it helps catch a whole category of bugs that might otherwise be hard to catch
even things as simple as typos in attribute names can be easily caught by the static checker, whereas otherwise they might not be caught until runtime
I see, interesting
static checkers include Mypy (the "original"), Pyre, and Pyright
I remember getting in trouble with a teacher once for writing one long list comprehension on one line instead of a program
you definitely belong in #esoteric-python lol
what was the circumstance, @hidden pewter?
The impression I get is that a lot of people who are currently employed in programming education don't actually use Python.
I forgot exactly but it was a bunch of for loops / if statements in a python basics class that I was overqualified for
ah
They said it was a readability issue
how long was the list comp?
I forgot
because if they've never seen a list comp that's kind of on them
I can't tell if I make decent or horrible code when it comes to readablity ๐ https://hastebin.com/ezuzotiriv.rb
which line?
I don't see the list comp but I'm exhausted and don't trust myself.
wow I feel gaslighted
Hey @unkempt rock!
It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
Dude
Readability. Does this count as readable
Do they not allow py
Can't even post a book to help people
I mean I can read that pretty easily
I think if you're not used to 1 liners it might look chaotic tho
Nah, seems pretty fine
The variable names make sense
Not stuff like x or y that no one could understand
@unkempt rock if you share a book here, it's probably just going to get lost in the chat history, but if it's a book that would be helpful for this community and the publisher is okay with distributing it for free we could talk about putting it on the website for this server.
I spent way to long trying to make that not completely unreadable. I think I succeeded, but it's a bit chaotic
That is what happens when you don't know about *args
@hidden pewter it seemed readable to me
I hate people complaining about having single letters as variables when working with physics stuff
Oh, I see, hm. Well I'm not the publisher so..
In physics, it makes sense, but general code ehh
a = ...
b = ...
c = ...
??
I hate that x y z don't always mean the same thing in space
y and z both sometimes mean up and down
excuse the not py:
const double g = 9.81;
const double G = 6.67430e-11;
double a = 0;
double Fg = 0;
double m1 = -1;
double m2 = -1;
double r = -1;```
This is C++ right?
yep
I watched someone make python code with c syntax. Why does python support that
?
cpython/cython
It's Cython
no not cython
python's also not written in python
they just put ; at the end and used {} instead of :
..What?
; extends the line (nvm)
it ends the line
it can just be slapped on the end like in c were it does nothing, because this is python
Yeah and starts a new one, I thought he was talking about in the map
; ends the statement but if you use it in Python you can have another statement before the new line
You can just do
!e
print('hello'); print('world')
@north root :white_check_mark: Your eval job has completed with return code 0.
001 | hello
002 | world
somefunc(); someotherfunc()
It's not wrong it's just ugly
also it could've been an OpenGL thing
Ah there
Is this python bot open source? I want to see how it evaluates from discord
!source e
Thanks
It just takes the text and runs eval
ok then
right ok
OH I remember on a different server had that. That ended well. Full server mute from bot
fOnere you guys ever do anything about people trying to delete the bot?
like excessively
"delete" the bot?
Is their a way to just sandbox code in python?
you can make a VM if that's what you mean
I meant like running eval without it being able to touch other code
I cba to find any but I've seen a few people try in bot commands
@signal tide Not even const double g = 9.80665 smh
No cause g depends on what body youโre on silly
Itโs only 9.81 on earth
I might not know what Iโm doing in cpp but I know my physics
It's 9.80665 on earth
just say 10
the average doesn't depend
Aren't we all in freefall at sea level at a geodetic latitude of 45 degrees???
Fg = 1/r^2
what am I reading?
advanced-physics-discussion
If youโre farther away from the body, the acceleration decreases in python
Sure, but the nominal accepted standard for g is 9.80665 m/s^2
it's entirely possible that I don't know what I'm looking at but I would encourage moving over to an off topic if needed.
Just like how pi isnโt just 3.14 (in python)
yes
How do I access it?
In math ya
Yeah, it does, but it'z LAZY
I think it's either from math import pi
It's just pi: 3.141592653589793
3.141592653589793
should be a double dont @ me
aren't floats doubles?
Yes
are there any use cases for pi in programming where more decimal places are useful, and which a computer can actually use?
In fact, this is a double because it's stored in C
I guess for scientific computing
Iโd assume some simulations depend on it being precise
Original definition is in a C file like so #define Py_MATH_PI 3.14159265358979323846
I remember reading that after some n digits of pi, you can calculate the diameter of the universe to the precision of the diameter of a proton, or something.
The python code is PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
After a while the curvature of space due to relativity is going to make your pi precision irrelevant anyway
C has long doubles so you can go deeper.
I've heard of long double precision needed for some deep mandelbrot zooms
I did a combinatorics problem in Python, the answer of which was an obscenely high number
apparently Python stores these as strings, or something?
I'm not entirely sure how that helps.
Because I don't think Python has a data type for over 64 bits of precision
So you'd store it as a string
Oh, apparently there's a bigfloat library
That makes sense. I'd have to look into the details to figure out how, a naive guess would be that you do math on X decimal places, multiply by 10^X, then do the math on the remaining decimal points
Right
but you can use decimal
or bigfloat
I mean, decimal is in the stdlib
but I don't doubt that the implementation is garbage
Can decimal handle more than 64 bit precision?
pretty sure cpython doesn't use opengmp or some similar library for big ints already
yes
Regardless chaos Iโm using 9.81, if I need the precision Iโll change it
Okay, cool
๐
I was just giving you shit, in engineering we always used 9.81 as well
engineering
e = 3
But technically it's 9.80665 and we can't get any more precise than that due to reasons
pi is always 3, i thought we all knew that
pi = e
No, pie are squared
Iโm going to cry
Hold on imma go throw up rq
Hold on imma go throw up rq
@signal tide Are you on the engineering side?
Oh god no
apparently not
probably more "pure math"
We engineers are known for our approximations and simplifications
I do โpure mathโ
We engineers are known for our approximations and simplifications
We know
Not everyone else has been exposed to the joys of engineering
engineer something in 5d then get back to me
I wonder how close you could get to pi if you used bigints and expressed pi as an integer ratio
are we counting computer scientists as engineers? because my desk (which I haven't been to since covid) is next to a chemical engineer's desk and I never know what she's talking about.
and chem ๐คญ atm Iโm looking at electronic energy transfer where energy is transferred from one molecule to another through space via virtual photons 
Chem is pretty nifty (with python or smth idk gotta stay on topic)
I wonder how close you could get to pi if you used bigints and expressed pi as an integer ratio
@pseudo cradle well infinitely close
Iโm building a generalised kMC framework to deal with it
Unfortunately; Iโm doing the whole thing from scratch
@signal tide she spent dozens of hours making a spreadsheet about how one chemical was synthesized by different chemists and my job at the time was to figure out how to automate that analysis in Python
but the person who was paying my advisor to pay me to do that dipped out when covid hit.
which is just as well because I had next to no idea how I was going to do it.
Thatโs sounds pretty interesting ngl
hah
I wanna do retrosynthetic analysis via graph neural networks
my work is natural language processing but I don't allege to have made any advancements in that field.
I've always found that fascinating
We've come such a long way in the last 20 years
except for the one I'm currently working on, but the only reason I made an advancement there is because I may have beat everyone to some low-hanging fruit.
I wouldn't have ever thought it was possible, but now I swear at Alexa regularly
I have a meeting with my advisors today ugh
and nice, that still counts
I should probably not make this conversation less relevant to the topic
let's see
@pseudo cradle have you seen flask-ask?
it's a Python API for Alexa. "ask" is actually an acronym for "alexa skills kit"
Oh nice
Right. I haven't touched webdev
the idea is that you can make your own extensions of flask, and flask-ask is a good example of that
Okay, cool
in fact by default it won't even handle requests that aren't from Amazon
call it fl-ask
lol
flask-ask maps the Alexa API onto Python really well
but that's mainly because the Alexa API is kinda garbage
lol...
so representing what little functionality it gives you can probably be done easily in any language.
you don't actually get what the user said
each voice command to Alexa that was intended for your program, you get a request
and that request doesn't contain anything that could possibly tell you what they, word-for-word, said.
well
when you're designing your Alexa app, you decide what sorts of things that app can do
you call these "intents"
and you tell Amazon what phrases can evoke those intents
Hmm
and all you get is what intent was evoked.
you can also have word slots, but you have to pre-define what words can go in those slots
you get that word
Making something like this sounds like a great way to differentiate yourself when applying for NPL job at amazon
have you been reading my diary?
Are you working on applying to Amazon?
I don't think my work would be useful for Alexa though.
I'm from where they're building the new Amazon HQ
Make sure you're up on your leetcode skills, they like to leetcode everyone regardless of level/experience
so working there would afford me the opportunity to move back
Nice
My attempts to keep myself on-topic aren't effective apparently so I'm going to head out of this channel unless someone has a new topic idea.
Help how do you capture the blue ~R and ^M characters from a unix file
with regex
these characters dont appear the same way
theyre just showing up as upside down question mar
There are different variations like ~Y or ~R that they might have used which show up as upside down question mark, I need a regex that only captures the upside down question mark
i tried just doing [upside_down_question_mark] but the problem is that this is the result of parsing that character, so I need to know what that character was to begin with to capture it
Hello everyone, this is a discussion channel, to discuss the Python programming language itself, from a higher-level perspective
It's one of the few channels we really like to keep on-topic for such discussions instead of help sessions
Hello Ves Zappa, where do you think it's best I ask this kind of a question then
Thank you for your help.
We have up to 32 help channels (see #โ๏ฝhow-to-get-help) and a bunch of topical channels to ask questions (see the Topical Chat/Help category)
Thanks! Am snek who is pretty new at python cuz it's been a year since I last coded
This is a very advanced discussion lol
lol
hello. i wonder if there is a (better) way or a style to raise TypeError in a function
e.g.:
def foo(name: str, age: int):
annotations = foo.__annotations__.items()
for arg, _type in annotations:
if not isinstance(locals()[arg], _type):
raise TypeError("'{arg} must be a '{correctType}', not a '{wrongType}'.".format(arg=arg, correctType=_type.__name__, wrongType=type(locals()[arg]).__name__))```
Thats not bad lol just would use f-strings
it would make it less verbose
TypeError(f"'{arg} must be a '{correctType}', not a '{wrongType}'.")
I wouldnt use f strings on anything that is going to be used as a external module for things
not for a while atleast
Is there a security risk?
so no special style to apply there ?
isn't leading _ for instance params in solidity?
leading normally to me suggests that its a explicitly unused variable
yep wasnt sure about the location of the _
trailing is normally to avoid naming collisions
leading typically means "private"
yeah private param
idk i have never used this before
i thought .format works better because it provides the repr of an object or something like that
I think he said no fstrings as places still require py<3.6
fstring is benchmarked to be faster in py>3.6
right if it requires py < 3.6 then you cant do it
sure it is, but i don't think speed is the issue here
I think he said no fstrings as places still require py<3.6
that would make sense, but 3.5 is becoming deprecated soon
and used with format notation because when working with variable
could you elaborate?
I only use .format for the backwards compatibility aspect
niceGuy = "{name} is the nicest guy alive"
niceGuy.format(name= "George")
and its useful sometimes for easy formatting
^ thats a very good reason lol
This is the equivalent
name = "George"
niceGuy = f"{name} is the nicest guy alive"
using .format for templating is fine as well
i find it more explicit when i look at my code
I would save the type checking in a decorator, to make your functions nicer to read
Right.. thats a valid point.
i was also thinking of a decorator, yeah
In [13]: from inspect import signature
...: from functools import wraps
...:
...: def ensure_type(func):
...: sig = signature(func)
...: ann = func.__annotations__
...:
...: @wraps(func)
...: def wrapper(*args, **kwargs):
...: bound = sig.bind(*args, **kwargs)
...: for name, item in bound.arguments.items():
...: if name in ann and not isinstance(item, ann[name]):
...: raise ValueError(f'got {item}, but {ann[name].__name__} required')
...: return func(*args, **kwargs)
...: return wrapper
...:
In [14]: @ensure_type
...: def test(x: int, y:str):
...: print(x, y)
...:
In [15]: test(2.3, 23)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-98815c19cc85> in <module>
----> 1 test(2.3, 23)
<ipython-input-13-b6238c366328> in wrapper(*args, **kwargs)
11 for name, item in bound.arguments.items():
12 if name in ann and not isinstance(item, ann[name]):
---> 13 raise ValueError(f'got {item}, but {ann[name].__name__} required')
14 return func(*args, **kwargs)
15 return wrapper
ValueError: got 2.3, but int required
ah... you got a float as x
I also think people ignore the % formatting systems alot aswell
thank you all for the discussion
I didn't know about this, very cool
https://www.python.org/dev/peps/pep-0593/
it would be nice if there was syntactic sugar for [v for k, v in d.items() if k in {k1, k2, k3}]
like d[k1, k2, k3] (where d is a dict)
so basically numpy-like indexing for dicts
d.items()
You could just subclass dict if you wanted
yeah, but then I wouldn't get that behaviour on literals
@gleaming rover one of these: https://toolz.readthedocs.io/en/latest/api.html#dicttoolz
Just do a check beforehand @gleaming rover
if isinstance(key, tuple):
...
else:
...```
Just do a check beforehand @gleaming rover
@dusty verge huh?
no, I mean
I wouldn't be able to define dict literals with that behaviour
@gleaming rover one of these: https://toolz.readthedocs.io/en/latest/api.html#dicttoolz
@spark magnet yeah, I know they exist...but I am greedy and want it as a language feature even though it doesn't make sense
Just do a check beforehand @gleaming rover
@dusty verge and it would be ambiguous
wdym by ambiguous
okay, I think that depends on your conceptualisation of passing multiple keys...but unlike numpy indexing, order does not matter, so in this case any iterable should be accepted as a collection of keys...?
there should be no distinction between tuples and lists as passed to __getitem__, unlike in numpy
in that case, it would not be possible to distinguish between a tuple key and a tuple as a collection of keys
Oh yeah, far out im stupid
Lol. my bad mate
I forgot that tuples are valid keys in dicts
but honestly all this wouldn't be a problem if we had dict destructuring
so back to {k1, k2} = d
I guess they could add dict intersection something like : d1 & d2 which could basically be the same as {k, d1[k] for k in d1.keys() & d2.keys()}?
But & is usually a symmetric operation, whereas this one wouldn't be - it takes the values from the left operand.
@safe hedge they added it in 3.9 or 3.10
@pearl river i dont like that argument, convenience beats purity in this case imo
They added dict updating and combination (with | and |=) in 3.9 but I donโt think thereโs intersection?
rightmost?
@pearl river l understand what youโre saying, but symmetric intersection of dicts seems like a bit of an odd case
Oh hey, there my argument is ๐
https://www.python.org/dev/peps/pep-0584/#dict-union-is-not-commutative
that kinda looks like a weird edge case caused by objects being compared by value regardless of type.
I mean, itโs there, but itโs been ignored haha
But thatโs a union, not a subsetting.
Iโm not convinced that & for dicts should be based on keys alone tbh
Set intersection (&) is a bit more problematic. While it is easy to determine the intersection of keys in two dicts, it is not clear what to do with the values. Given the two dicts above, it is obvious that the only key of d1 & d2 must be "eggs". "Last seen wins", however, has the advantage of consistency with other dict operations (and the proposed union operators).
yup, exactly the same problem - not symmetric.
^Yeah thats what Iโm saying
I think & is the best I can come up with, but there would be inherent oddness about it
yeah so i dont understand why its ok for | and not for &
alternatively it could just KeyError when there are overlapping keys ๐คทโโ๏ธ
Could you maybe use | and & for keywise and || and && for key+valuewise?
|| and && don't even exist, do they?
Tbh I donโt even really like using that notation for most things because I donโt think itโs that readable to the average python user
like, they can be implemented, but through a hack with double application of &
@pearl river not right now, no
Like, I think even if this was an option I donโt really see that doing {k: d1[k] for k in d1.keys() & d2.keys()} is that problematic to write
also, if dict intersection/union would be implemented, but only explicitly:
d1.intersect(d2)
it would make it far clearer that it's not symmetric.
I mean, yes and no
Looking at that function I still donโt have a clear indication if it includes all matching keys or just matching key:value pairs
You would have to have .keyintersect() and .intersect() maybe
What if it would produce a dictionary with the keys being the overlapping keys and the values being tuples of values from both dicts? e. g. {"a": 1, "b": 2} & {"b": 3, "c": 4} == {"b": (2, 3)}
Although it's definitely not going to work well if you chain intersections
to the deleted message: then dict would not be a good choice in the first place, a set would
@spice pecan that might be nice behavior for a multi-dict
like what the various http libs use for http headers
also shoutout to the bidict library which is one of those underrated gems
anti-shoutout to the lack of frozendict in the python stdlib
and anti-shoutout to the fact that there are 2 competing ordered set implementations on pypi, both based on the same activestate recipe by hettinger
bidict library
oh, nice.
that kinda looks like a weird edge case caused by objects being compared by value regardless of type.
@pearl river that's just because they are equal and have the same hash, right?
>>> {0, False}
{0}
well, if 2 things are equal and hashable, they must have the same hash
yup. They say "the results may be equal but are distinctly different", but it's them being equal that creates that behavior in the first place.
In [5]: fractions.Fraction(1, 2) == 0.5
Out[5]: True
In [6]: hash(fractions.Fraction(1, 2)) == hash(0.5)
Out[6]: True
```I do wonder how that is actually accomplished internally
def __hash__(self):
"""hash(self)"""
# To make sure that the hash of a Fraction agrees with the hash
# of a numerically equal integer, float or Decimal instance, we
# follow the rules for numeric hashes outlined in the
# documentation. (See library docs, 'Built-in Types').
try:
dinv = pow(self._denominator, -1, _PyHASH_MODULUS)
except ValueError:
# ValueError means there is no modular inverse.
hash_ = _PyHASH_INF
else:
# The general algorithm now specifies that the absolute value of
# the hash is
# (|N| * dinv) % P
# where N is self._numerator and P is _PyHASH_MODULUS. That's
# optimized here in two ways: first, for a non-negative int i,
# hash(i) == i % P, but the int hash implementation doesn't need
# to divide, and is faster than doing % P explicitly. So we do
# hash(|N| * dinv)
# instead. Second, N is unbounded, so its product with dinv may
# be arbitrarily expensive to compute. The final answer is the
# same if we use the bounded |N| % P instead, which can again
# be done with an int hash() call. If 0 <= i < P, hash(i) == i,
# so this nested hash() call wastes a bit of time making a
# redundant copy when |N| < P, but can save an arbitrarily large
# amount of computation for large |N|.
hash_ = hash(hash(abs(self._numerator)) * dinv)
result = hash_ if self._numerator >= 0 else -hash_
return -2 if result == -1 else result```
neat
you know it's a clever implementation when there's 20 lines of comments for 9 lines of code ๐
I am pretty sure the first hash is just used as modulo
ah, you misread, it does hash(hash(x) * y)
oh duh
Hi, I need help with python
Does anyone know how to code:
A guessing game that uses alphabets in place of digits to make a puzzle out of the addition of two single-digit numbers and the answer. The letters a to j are randomly ordered and each digit 0 to 9 are represented by corresponding letters by position. The player solves the puzzle by guessing which digits fit into the puzzle.
@sly geyser This isn't the place for homework. Yes we know how to code simple games. This isn't the place for that.
Ok thanks wrong group then
anyone here with an experience of scraping pdfs? i want to parse pdf tables with very odd formatting, there are 2 types of column in one table (!) each of different width, multirow cells and also multicolumn cells, on top of that tables span across multiple pages
any ideas how to approach this task?
@unkempt rock this isnt really the right channel for that, maybe ask in #tools-and-devops ?
@paper echo alright, i'll head there, thanks
seems like a messy problem too, so good luck
how accurate are python's floating points?
like, isn't there a number of digits that it can't represent past?
they follow ieee754
they're doubles
oh lol

oh it's 15 and 7 for doubles and floats respectively
huh?
they do not have decimal significant digits
you can have decimals with arbitrary precision with https://docs.python.org/3.8/library/decimal.html
whats something that can be used for background tasks in python
celery? or other alternatives out there
@boreal mantle You can ask in #tools-and-devops, I suppose
depends on the background task. a simple cron job can suffice if that's what you need. celery is fine too but it's hard to configure. you could also look at message queues, i.e. ZeroMQ or RabbitMQ, and set up a pipeline.
Guys I want to ask, how can I send email without using smtplib? Because I have a python interview. He told me for making python scripts using standard python library for sending email but not using smtplib. It can be a honor if you guys can give me a solution. Thanks
Guys I want to ask, how can I send email without using smtplib? Because I have a python interview. He told me for making python scripts using standard python library for sending email but not using smtplib. Any solution guys? Thanks
@rare wren make a request to gmail api
so I was thinking...is pass really necessary?
what if ... was used in its place?
so like:
def stub():
...
pretty sure id give an error
!silence
โ silenced current channel for 10 minute(s).
โ unsilenced current channel.
he used on emoji lmfao
elipses typically mean that something is abbreviated, or that there is more information available, so it doesn't really fit with being the same as "pass"
one*
no i deleted it
ohh
just in case
!tempmute 360548278313549825 12H Continued off topic noise in topical channel
:incoming_envelope: :ok_hand: applied mute to @dusty jungle until 2020-08-27 13:48 (11 hours and 59 minutes).
right im working on a python project
pretty sure id give an error
@ocean palm no, it would not.
a literal in statement position is not a syntax error
but neither does it do anything
yup, so I'm clarifying that it wouldn't
elipses typically mean that something is abbreviated, or that there is more information available, so it doesn't really fit with being the same as "pass"
@stoic wyvern or that something "remains to be filled in"
like my PoV is that there are actual good uses of the word "pass", and it wouldn't be backward compatibility-breaking
and honestly adding ... just for numpy is a little weird
Hmm, upon looking up the definition of ellipsis, yeah that could work
numpy is so worth learning for python
like it just removes the while
whole
speed concern
cuz itd C code
but its so much easier to work with
...fr?
depends on what you want to do
again havent gotten there yet
#bot-commands
anyway, we should probably talk about this in #data-science-and-ml
yea good idea
I saw you guys talking about matplotlib and numpy ? I learned Matlab and it's really similar but python is free so i was wondering if there is any cons ? Or why would they make matlab with a paied license ? is it faster or something ?
isnt it double license tho? Like - paid for companies and free for non-business use
I saw you guys talking about
matplotlibandnumpy? I learned Matlab and it's really similar but python is free so i was wondering if there is any cons ? Or why would they make matlab with a paied license ? is it faster or something ?
@hybrid path not really.
I mean, there are differences in usage
isnt it double license tho? Like - paid for companies and free for non-business use
@loud tapir no i think it's only free for students if your university purchased the education license but otherwise i don't think it's free
I was curious because i am seeing more and more AI papers using Matlab for there demos instead of Tensorflow and Python
The real question is why you're not using R for making graphs ๐
Is R better for graphs
@unkempt rock each to their own tbh. But imo ggplot is still the best static graphing library
I have used plotly in both R and python for making HTML graphs and I do find python easier when generating more dynamic plots
so Iโm not an experience programmer at all but what are the advantages of R
I know that itโs mainly for statistics and data science
Anyone got a 3.8 alternative for Kivy since it wasnt ported?
@unkempt rock we probably shouldn't have an extended discussion on that here. But ultimately it tends to be better for implementations of statistical testing
Hey guys, I was trying to help @rare wren with a job question. he has to send an email without smtp, but idk how to help him and i dont really want to let him down. ive found it kinda difficult
using only the standard libraries
and yes, ik that smtp is part of the standard library ๐
I'm not really clear what you mean tbh
Do you want to send the email without using SMTP at all or just without using the stdlib smtplib?
Do you want to send the email without using SMTP at all or just without using the stdlib
smtplib?
@safe hedge
Using another standard python lib except smtplib bro
I mean... You could just use subprocess to call mail or whatever from the commandline
Seems like a bit of a cheat though
I mean... You could just use subprocess to call
@safe hedge
Hmm can you elaborate me bro
And this person used sockets by the looks of it
https://stackoverflow.com/questions/33397024/mail-client-in-python-using-sockets-onlyno-smtplib
Seems like a pretty tricky question for a job, not that I really do anything advanced with email, and if you are really struggling with it you might want to consider whether it's a role that's best suited to you
I mean... You could just use subprocess to call
@safe hedge you can use subprocess to call literally everything. But there may be some os-exclusive shenanigans in tools you are calling, so its generally not a good idea, unless necessary
I'm well aware of that. But honestly I suspect calling subprocess and running a standard mail tool is actually going to be wayyyyy more robust than trying to roll your own smtplib alternative
The real question is would whomever is asking the question consider that an acceptable answer
I mean, isn't the whole reason one is using python to do it as compared to other languages likely related to the robust imports you have access to?
Yeah
I once had an interview task that involved manipulating some text and csv files. I used csv from the stdlib to parse them and the interviewer asked me if I would normally just import libraries to solve a problem. Like, yeah, do you really want me to spend my paid time redesigning the wheel pal
also stdlib seems like a pretty safe dependency as well...
oh, @loud tapir I don't know if you ever responded to my question about interpreters in the python-general chat, but I completely missed it if you did
I looked away for a few minutes, and, well
oh, @loud tapir I don't know if you ever responded to my question about interpreters in the python-general chat, but I completely missed it if you did
@safe linden I was just hoping that someone else will response :D
ah gotcha. one person did and they set me on the path of reading about CPython, that's why I missed general. I think my main mistake of thinking there was a single standard for interpreters has been corrected. I can probably follow up more with that on my own.
I'm still sort of convinced that numpy arrays are actual arrays and python arrays are just structs though
some behaviour of interpreters is exclusive to particular interpreters, so I assume most of things are up to whoever make them
the data is stored consecutively in memory
I'm not sure about the Array class in Python, but if it doesn't let you declare a datatype then it's just an array of pointers
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Huh, !e restriction in advanced discussion is interesting
@pseudo cradle I am confident numpy arrays are, but are the default python arrays actual arrays?
I believe they are, since you have to declare a data type
If you didn't have to declare a data type it would be a dead giveaway
But they don't require a length set, and they seem to accept additional elements?
Yeah, everything I'm reading here indicates to me that they are. Oh, I see what you mean.
I'm guessing they're dynamic arrays
so i guess my better question
are python arrays concatenated in memory?
and that answer is maybe "depends on the interpreter"?
thank you very much
๐
Both CPython array module arrays and Python lists are dynamic arrays. list is a dynamic array of object references, and array module arrays are dynamic arrays of fixed size native objects like 32 bit ints
What is the best approach to create a rule engine with concrete rules ? Like java has drools
How to send email only with socket ?
@safe hedge
In [32]: def test():
...: c = 3000
...: d = 3000
...: print(c == d)
...: print(c is d)
...:
In [33]: test()
True
True
In [34]: test.__code__.co_consts
Out[34]: (None, 3000)
(cont from #community-meta )
functions cache all constants in their code. If you for example had
In [35]: def test():
...: c = 3000
...: d = c + 0
...: print(c == d)
...: print(c is d)
...:
In [36]: test()
True
False
it does not do that, because d is computed anew, rather than just loading the cached constant
@surreal idol just so happens I linked this in here earlier: https://discordapp.com/channels/267624335836053506/709904092280914030/748371099410235475
@flat gazelle Ah nice. I assumed it must be something like that. I guess that's the same reason
a = 257
b = 257
print(a is b)
and
a = 257;b = 257;
print(a is b)
behave differently
ye, the shell compiles line by line
!e ```python
from dis import dis
def f():
return 5e12
dis(f)
@paper echo :white_check_mark: Your eval job has completed with return code 0.
001 | 3 0 LOAD_CONST 1 (5000000000000.0)
002 | 2 RETURN_VALUE
!e ```python
from dis import dis
def f():
return 5e12
def g():
return 5e12
print( f() is g() )
@paper echo :white_check_mark: Your eval job has completed with return code 0.
True
nice
TypeError: a bytes-like object is required, not 'str' ```
Can anyone help me to fix this issue?
@brisk warren you should ask this question in a help channel, see #โ๏ฝhow-to-get-help
@paper echo I think you've been bamboozled:
>>> def g():
... return 5e12
...
>>> def f():
... return 5e12
...
>>> print( f() is g() )
False
๐ฎ
@flat gazelle explained it in the #community-meta channel where I originally asked about this
In [42]: def test():
...: from dis import dis
...: def f():
...: return 5e12
...: def g():
...: return 5e12
...: print( f() is g() )
...:
In [43]: test()
True
```same thing as before
It's because the code is compiled when you do !e
@paper echo don't have permission to ask on that channel
@brisk warren read the content there.
ah, bamboozled indeed
fwiw how often are we running python code that hasnt been pyc'ed first?
Is that even possible?
it is not
apparently in the repl? or do i misunderstand what we mean by compiled
in the repl, each function gets compiled separately
is the idea that any code that gets compiled in the same pyc file will share constants?
I would expect the only way to get f() is not g() is to have them in distinct files
And the code gets compiled line by line in the REPL, so it gets optimized, but each line separately
In [44]: exec("""from dis import dis
...: def f():
...: return 5e12
...: def g():
...: return 5e12
...: print( f() is g() )
...: """)
True
```even in a module they share constants
In [45]: exec("""def f():
...: return 5e12""")
In [46]: exec("""def g():
...: return 5e12""")
In [47]: f() is g()
Out[47]: False
@flat gazelle or just running it in the interpreter:
>>> def g():
... return 5e12
...
>>> def f():
... return 5e12
...
>>> f() is not g()
True
>>>
ye, but that does not happen in actual code
This behaviour is all just an implementation detail anyway right
yes
Does anyone now a good library to play audio streams from internet radios?
this channel is meant for discussing python itself, for help see #โ๏ฝhow-to-get-help @stoic trail
Who pinged me in general?
I fail to see hows that relevant to this channel
;(
random.seed = (os.urandom(1024))
python
can anyone explain what it mean??
You change the seed of the random module (the base for all the random output, with the same seed you'll have the same result) to be a random value provided by the OS, considered safe but slow
You don't need parenthesis around os.urandom(1024) btw
And... We are in the wrong channel, my bad
Decided to move my question here as general seems really active atm (still).
so, about Python GUIs.. Not sure if Iโve asked this before...
Edit: moved again
There are a lot of Python bindings for GUI frameworks out there; there's probably something you like. A lot of people like QT. Also, you won't get a lot of response here, because this channel is meant to discuss the Python programming language itself, from a higher-level perspective. If #python-discussion is too crowded, consider opening a help channel or using the #user-interfaces topical channel.
Crap I didnโt see that channel. Would you be okay if I moved it again (and maybe delete from here)? @wide shuttle
Sure
๐
How can i get Smtp server and port from email address in python ? I wanna make email service with that.
I've personally never worked with that but you could try this: https://docs.python.org/3/library/smtplib.html
you should be able to make a listener on some given host and port with that library,
from there it should be easy to access the calls to it
I wanna do like when email sender is "bussiness@mywebsite.com" then i will get smtp server that email.
I wanna do like when email sender is "bussiness@mywebsite.com" then i will get smtp server that email.
@surreal idol is that possible ?
i developed a solution on a raspberry pi but the company wanted the code written in C# i searched online and i found ironpython but i don't really have an idea if this is possible to convert python code to c# without rewriting the code, your thoughts and your suggestions?
no its not really possible
ironpython is a maybe, but python3 support is still not ready
and even then, i dont believe iron python converts into c#
ironpython is an implementation of the python lang that communicates with .net framework, and in that vein im not sure if it even has core support
which if you are on a pi is probably what you want
basically im saying you have to rewrite it
guys i am doing a project which uses Real time video processing please share some document cxz google is not helping what i have to do with RTVP is to count the no of vehicles\
Hi everyone! I have a question to ask.
I have been programming in Python 3 for last 3 years, and I love it.
@unreal jackal See #โ๏ฝhow-to-get-help for more general questions, unless what you were going to say fits the topic
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.
I want to make a kinda generic threading system where you pass in a multiple-parameter function, and one parameter becomes a list, and thatโs the thing you thread on, with futures
Surely this is a solved problem
Just need some help/guidance
I want the generic threader to return a list of results whose elements would correspond to each individual function call
so it would be something like
pool([f1, f2, f3, f4]) -> [f1(), f2(), f3(), f4()]
```?
Kinda, yeah
And then I want to be able to describe f1, f2... as a list of functions built on a list of one selected parameter of f
So if its f(x, y) I want to be able to say f1 = f(X1, y), f2 = f(x2, y) etc etc
Or could be y1, y2, etc
Isn't that just the map function of the multiprocessing library?
is there some sane way to execute python from the command line such that the last executed expression/statement is returned, like in the python console & ipython?
python -c "x=3; y=4; x == y"
something like this, but where the result of x == y is printed without having to explicitly wrap it in print( ... )
can i do this with the code module somehow?
!d g code
Source code: Lib/code.py
The code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications which provide an interactive interpreter prompt.
if you just want to see the result and not use it in a script, piping to python -i does do something marginally similar, but it is not great solution by any measure
python -c 'import code; code.InteractiveInterpreter().runsource("x=1;y=2;x==y")'
i think i got it ๐
PS C:\Users\adamh\Documenty\politika> echo "x=5;y=6;x+y" | py -m code -q
>>> 11
>>>
now exiting InteractiveConsole...
``` still noisy, but probably somewhat usable
oh interesting
is that in the docs?
it would be nice if they had a flag to disable the >>> stuff
and the "exiting" message
I feel like I remember there was a way to change that symbol
that seems worth suggesting, probably not a PEP though
Actually I'm quite confident it's a variable that can be set.
nah could be a good patch for 3.10 though
not to mention documenting -m code...
i have uh
a "bad idea" in mind
im writing in ZSH right now but it could/should be rewritten in python itself
Aren't the >>> an env var?
I was half afraid of what the esoteric community would do with it as I shared that link, not gonna lie ๐
could have been way worst ยฏ\_(ใ)_/ยฏ
But I'm sure we can do some stupid things with that
I subclassed interactive console when making a kivy python interpreter --- prompts could be set as class variables
Could easily insert a mangled unicode string there and python wouldn't bat an eyelid while the end user would think something is seriously wrong.
could run arbitrary code too
>>> import sys
>>> class U:
... def __str__(self):
... print('ping')
...
>>> sys.ps1=U()
ping
ping
print('Hello World')
Hello World
ping
depends on the terminal emulator, windows terminal probably yes, other windows no, linux I have no idea
they don't exist like they do in a language like java
wow
There's a @salt-die code snippet for everything, apparently
you're not wrong
you can use dictionaries for a similar purpose
there's also the new pattern matching pep
I hope this is implemented
this would be pretty cool yes, but dicts do generally get the job done I think
they just don't have fall-through, i don't think the pattern matching does either
or maybe it does
i'd have to re-read it
I think it does, if I remember correctly
actually now I'm not sure
ok it doesn't apparently
However, we don't want to mislead people into thinking that match/case uses fall-through semantics (which are a common source of bugs in C).
Essentially this is equivalent to a chain of if ... elif ... else statements.
I made the very academic switch case above just to have a fall-through
I don't have a use-case for it though, probably way too meta
Heh, definitely a common source of bugs in assembly, but even then it's an expected desired trait in a lot of instances
Does anyone like or follow pep8's 80 char rule per line?
I do sometimes follow it in simpler projects, but in a lot of cases you want a more sensible maximum
I heard some people like 240
240 is far too much unless you have really long names
general guideline I use 90-100, 110 when calling long names
it is annoying with long var names
the only reason I sometimes stick to 80 is because that is the default and for simple projects changing it is a PITA
120 is the most I've seen used widely, there aren't that many things that will have a better readability beyond that
130 is like tops imo
If you're running into line len limits because of long var names then it may be a sign that they're a bit too verbose
typing this does not work well when you use the 80 char limit python self.write_value = self.epp_variables[template_name[0]].var_output(self.parse_parameters(template_name[1][:-1]))
That looks like a fairly busy line that could be separated out
it look so complex beacuse self.long_var_name
a = b[c[0]].o(g(t[1][:-1]))
```is not any better
the line could be breaked up in var_output() call
@flat gazelle There needs to be a fine balance between long and short names
i would do something like this
epp_variable = self.epp_variables[template_name[0]]
parameters = self.parse_parameters(template_name[1][:-1])
self.write_value = epp_variable.var_output(parameters)
the line you showed is far too crowded for my liking
my point was that it was not complex because long names, even with short names it is a complex expression
I think f1re's example is best for understandability. I don't like creating vars that only get called once though
One of the purposes of the line limit is to prevent that many operations in one line, you're doing 3 accesses, 2 function calls, slicing and an assignment all at once
vars the are only used once are perfectly fine
Keeping the average length small is also important.
If every line is 79 characters long, it's pretty unreadable
i would probably unpack template_name too
raymond hettinger's beyond pep8 talk talks about the line length thing a lot
I think the 79 character length is an archaic restriction that was necessary when wide screen monitors weren't the norm and terminals had fixed text size, etc.
Completely unnecessary anymore
120ish seems like a good upper end just from practicality and readibility
Pep8 lists some advantages of that limit, I think.
Mainly horizontally splitting the view.
And, as mentioned above, a line that long might be the result of cramming too much in one line.
Also, not everyone is going to view the code on a 4k display
79chars wasn't and isn't about widescreen monitors. It's 79 chars because that's how big a standard terminal is
This is from my laptop with a 15in monitor, with VSCode set to the dimensions I'm comfortable with. It can only fit 80 columns. If I close the file explorer, it can only fit 108.
btw I'd be super stoked if they upped the pep8 char limit
I don't think it would change anything, pep8 is not anyone's boss ๐
dress up as pep8 for halloween
people will just ignore me
The limit I fix myself is 100 to be able to split a standard screen in 2
With the added restriction to not nest any function / method calls
how do you reach 100 characters then? ๐
with_a_really_long_variable_name.and_unbelievably_large_method_name(with_a_lengthy_argument_as_well)
?
Seting up an API with local host using python to use in flutter,
Is only useful before I publish app, because after publishing, I can't run the api for some other and can't keep my computer on,.
So how I do so without spending money on buying a new web hosting or something like that
hi--if a library wants to expose a bunch of ideas to the outside world, for example
foo/
__init__.py
bar/
baz.py
...
is there a better way for third party applications to do things like from foo import Baz than putting all the imports in __init__.py a la from bar.baz import Baz or is that the prescribed way?
looks like flask does it, so i suppose it is
that's how i do it, cause i dunno another way
there isn't really any other solution I guess
I'm a big fan of including certain things in __init__.py. We have a bunch of pandas accessors at work, and we include them in the top levle __init__ so that when you import the module, the accessors are automatically added to the namespace.
Is transpiled Python-to-JS allowed? I read through the rules and it says "other code is fine as long as it doesn't implement game logic". Where is the line between what constitutes as Python and what counts as "other code"? Is the transpiled code still Python if the original source code is Python?
This project in particular seems interesting: http://www.transcrypt.org/examples
Transcrypt Numscrypt code examples of using various JavaScript libraries.
maybe you meant to post in #pyweek-game-jam
How do I implement a python algorithm that bounces when it hits the edge of the screen?
if x_cord > x_bound: dont()
if x_cord > x_bound: dont(); turn_around(); go_back()*
I hope those are built in functions
Otherwise you're just moving the work of implementing that somewhere else
you've never using go_back()? ๐
Moving the work around is like 90% of programming :)
does anyone know if mypy is the best type checker for python? or is there another one out there?
there also exists pytype
When I asked why mypy is considered the "default" as far as type checkers go, I recieved an answer that was obvious in hindsight:
Yup, mypy is maintained by the PSF
oh
i know it's not perfect, but at times, it's pretty buggy once you start using more nested types
just thought there was a more robust one
PyCharm goes crazy when I start using generic callables
why is bool a subclass of int?
1 or 0โข๏ธ
I like sum(map(f, iterable)) as much as the next person, but seriously
for reverse compat. Python used to not have a bool and just used 0 and 1
I like this summary:
To sum up True and False in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that str() and repr() return the strings 'True' and 'False' instead of '1' and '0'.
I like languages where they're separate types, I guess
why?
@vale summit there is also pyright and pyre
why?
@sacred tinsel kind of smacks of weak typing, I guess?