#internals-and-peps
1 messages · Page 75 of 1
you want instances of the child class to be stored as a class attribute in the parent class?
Yeah
but I'm realizing I think this is ill-thought, so I'm just going to capture the module and name of the child. @gleaming rover
but I'm realizing I think this is ill-thought, so I'm just going to capture the module and name of the child. @gleaming rover
@swift imp but my esoteric Python 😦
Hey man, I'm all ears
@swift imp
class Parent:
child_instances = []
def __init_subclass__(cls, **kwargs):
def init_hook(self, *args, **kwargs):
old_init(self, *args, **kwargs)
Parent.child_instances.append(self)
super().__init_subclass__(**kwargs)
old_init = cls.__init__
cls.__init__ = init_hook
you could use weak references, I guess
very very interesting my friend, I like this A LOT more than storing name and module of the child class.
maybe old_init, cls.__init__ = cls.__init__, init_hook shrug
also if anyone has any ideas how to point to the current class without using the name Parent specifically...that'd be nice
Well wait, this still has problems.
Well wait, this still has problems.
@swift imp what?
So like I'm using the **kwargs of __init_subclass__ as indicators to what child class to use for processing. Now I store those kwargs.values() in a frozenset and that becomes the key within an internal dict of the parent. What I want is for a child instances to be the values of that internal dict. Basically the top level module gets fired up, pulls some specific attributes from a file and then uses those attributes as a key to that internal dict of parent. So like child will never actually get instantiated on its own to make that init_hook go off.
right
you want instances of the child class to be stored as a class attribute in the parent class?
@gleaming rover so you want to store the child classes themselves?
hold on
I thought you said you wanted instances of the child class
Ideally, an instance would be perfect
but the way I'm storing the instances with your method
Like the instance wont get stored until its instantiated
yup, because it wouldn't exist otherwise, right?
that's the earliest an instance can exist
But in my case, child would never get instantiated by itself
Does that make any sense?
So like I'm using the
**kwargsof__init_subclass__as indicators to what child class to use for processing. Now I store thosekwargs.values()in afrozensetand that becomes thekeywithin an internaldictof the parent. What I want is for a child instances to be thevaluesof that internaldict. Basically the top level module gets fired up, pulls some specific attributes from a file and then uses those attributes as akeyto that internaldictofparent. So likechildwill never actually get instantiated on its own to make thatinit_hookgo off.
@swift imp I understand this
but it sounds like the values within said internal dict would be classes, right?
the said child classes above
i.e. not the instances
@gleaming rover yeah it would be the cls and not an instance of cls, which is a problem because then @abstractmethod doesn't go off.
This is a work in progress but its my general idea
@gleaming rover yeah it would be the
clsand not aninstanceofcls, which is a problem because then@abstractmethoddoesn't go off.
@swift imp any other problems with storing the classes?
because I think that's a more sensible approach
@abstractmethod doesn't go off, if the property isn't defined
other than that
assert all(not getattr(cls, attribute).__isabstractmethod__ for attribute in dir(cls))
right, because if its been redefined properly then __isabstractmethod__ should never be True
I didn't know you could do that!
Tyvm. Gonna delete that code bc its for work lol
yw 🙂
Hey guys, can someone help me with this https://dpaste.org/JmjH - not sure what im missing :`\
Hey guys, can someone help me with this https://dpaste.org/JmjH - not sure what im missing :`
@unkempt rock this is a discussion channel; you might want to try #❓|how-to-get-help
oh thanks,
How are the stacks organized in the official CPython interpreter? I know there is a call stack that stores different objects, and that each frame has its own data stacks, but beyond that I have no idea.
@heady mauve the call stack is a linked list of frame object.
and now that you mention it, i'm not sure each frame has its own data stack.
also no shock youre the one to respond given you wrote byterun XD
there's also a block stack, for each loop
(I just happened to peek in right after you asked 🙂 )
in byterun, the Frame object has a stack attribute. but in CPython, the frame objects don't.
interesting...
maybe cpython has them but doesn't expose them?
why dont I ask a core dev? :P
(or read the source:) PyObject **f_valuestack; /* points after the last local */
fair
in frameobject.h
ok, so: call stack, data stack per frame, and block stack per frame
nice
you got that from https://github.com/python/cpython/blob/cb9879b948a19c9434316f8ab6aba9c4601a8173/Include/cpython/frameobject.h ?
the two "per frame" values are there, yes
thanks!
@spark magnet mind gimme some of your thoughts on an issue I currently have? I saw different blogs, docs, etc. but I still can't figure out a piece of code
#❓|how-to-get-help @unkempt rock
so are we actually going to be getting match with pep 622 in 3.10? (https://www.python.org/dev/peps/pep-0622/#version-history)
can't tell if that's been accepted yet
the status says draft, but it specifies the version as 3.10
@silk pawn the version number just indicates which version of Python the proposed functionality would be introduced into.
if it were approved right now (and it appears that it hasn't been), there wouldn't be enough time to include it in 3.9.
From the gossip I've heard, the steering committee is still pretty divided on it.
I haven't really read how it works but the idea of adding soft keywords is a big red flag to me.
and I've never encountered a circumstance where chained if statements weren't perfectly fine
Switch statements have an advantage over chained if statements in that they can be compiled into a lookup table, so you don't need to check every condition... But, the proposed match statement won't do that.
(if you need a switch statement for its performance in Python, it's common to use a dict of functions as your lookup table)
But, the proposed match statement won't do that.
@raven ridge so what's the point? syntactic nicety?
The point is to bring pattern matching to Python. It seems to be done in a way that's sort of crippled compared to pattern matching in other languages, though.
I still really want function composition and except-with, but big changes are scary
what is function composition
except with?
composition:
In [11]: f = 2 * x
...: g = 2 + x
...: f.subs({'x': g})
Out[11]: 2*x + 4
what is function composition
@mint forge the idea is that(x @ y)(n)would be the same asx(y(n)). you could chain as many functions as you want as long as the value returned by each one is usable by the previous function in the chain.
sympy
ohhhhhhhhhhhhh
@ was introduced as an operator recently for matrix multiplication in numpy, but @ is already used for decorators and this is along the same lines.
@sacred yew except-with is just my proposed syntax for inline exception handling
I do a lot of math-y stuff with python and even I don't think I'd use a composition operator that much
var = my_list[8] except IndexError with 3.14
in-line excepts might be ok, i'd rather have none-aware first
so if my_list[8] raises IndexError, you replace it with the value after the with. There was actually a pep along the same lines but the proposed syntax was var = my_list[8] except IndexError: 3.14, though there was tons of bikeshedding.
no one proposed except-with and I'm not sure why. the only other existing keyword that I think could be sort of appropriate is as but that already has a specific meaning in the context of exception handling.
should be else
I don't like the use of the colon in the proposed syntax. Guido rejected it, but I think more because he was opposed to the concept of inline exception handling
why else?
looks familiar
I would interpret that to mean "this is the value you use if you don't get the given exception"
var = my_list[8] except IndexError else 3.14
"if you don't except IndexError (because you didn't get it), the value is 3.14"
3.14 except IndexError else my_list[8]
that treats the "excepted" value like that's what you expected it to be
from types import FunctionType
from typing import Callable, TypeVar
from forbiddenfruit import curse
T = TypeVar("T")
U = TypeVar("U")
V = TypeVar("V")
def chainer(f: Callable[[U], T], g: Callable[[V], U]) -> Callable[[V], T]:
def wrapper(value: V) -> T:
return f(g(value))
return wrapper
curse(FunctionType, "__matmul__", chainer)``` eeh
cursed but it works
and the expression that's being tried comes after the exception that it might raise
annotations makes it take twice as long for me to read
Hm, I kinda like except/with. I'm sure there are times I would have used it if it existed.
x ??= something
annotations makes it take twice as long for me to read
@deft pagoda oh, I am hugely into rust here, so... heh
inline exception handling of some kind, func comp, none-aware
anything else we need before Python can have its final release?
In [12]: from inspect import currentframe, getframeinfo
...:
...: def maybe(val):
...: parent_frame = currentframe().f_back
...: line = getframeinfo(parent_frame).code_context[0]
...: var, sep, _ = line.partition('=')
...:
...: if not sep:
...: raise SyntaxError('maybe(val) needs to be called in an assignment expression')
...:
...: glob = parent_frame.f_locals
...: loc = {}
...: exec(f'val = {var}', glob, loc)
...:
...: return val if val is not None else loc['val']
...:
...: x = 3
...: x = maybe(None)
...: x
Out[12]: 3
fn compose<F, G, T, U, V>(f: F, g: G) -> Fn(V) -> T
where
F: Fn(U) -> T,
G: Fn(V) -> U,
{
move |value| f(g(value))
}``` just an example, haha
anything else we need before Python can have its final release?
syntactic macros and pattern matching, please
pattern matching pep probably needs some revision before it gets accepted
indeed
i'd like dict-xor
hm idk
>>> from iters import iter
>>> iterator = iter(range(10))
>>> dir(iterator)
['__class__', '__class_getitem__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__orig_bases__', '__parameters__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_is_protocol', '_iterator', 'all', 'any', 'append', 'chain', 'collapse', 'collect', 'compress', 'copy', 'copy_infinite', 'copy_safe', 'count', 'cycle', 'cycle_infinite', 'cycle_safe', 'drop', 'drop_while', 'enumerate', 'exhaust', 'filter', 'find', 'find_all', 'first', 'first_or', 'flatten', 'fold', 'for_each', 'get', 'get_all', 'group', 'group_longest', 'inspect', 'inspect_format', 'iter', 'iter_chunk', 'iterate', 'last', 'last_or', 'length', 'list', 'list_chunk', 'map', 'max', 'max_or', 'min', 'min_or', 'next', 'next_or', 'nth', 'nth_or', 'nth_or_last', 'partition', 'partition_infinite', 'partition_safe', 'prepend', 'product', 'reduce', 'repeat', 'reverse', 'reversed', 'set', 'side_effect', 'skip', 'skip_while', 'slice', 'star_map', 'step_by', 'sum', 'take', 'take_while', 'tuple', 'tuple_chunk', 'unwrap', 'with_iter', 'zip', 'zip_longest']```
I kinda liked the idea of OOP iterators, and so I made just that hahaha
>>> (
... iter(range(10))
... .filter(lambda n: n % 2)
... .inspect_format("odd: {}")
... .map(lambda n: n * 2)
... .inspect_format("double: {}")
... .sum()
... )
odd: 1
double: 2
odd: 3
double: 6
odd: 5
double: 10
odd: 7
double: 14
odd: 9
double: 18
50``` allows doing fun stuff
@deft pagoda what would that do
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
x ^ y # {'a': 1, 'c': 4}
the keys not common to both
I would've used it a few times --- working with random data structures, I'm not sure I can pull a use-case out right now
I wouldn't want dicts to use set operators in a way that isn't as close as possible to how the same operator is used for sets
so I guess I'd be fine if they added that
but it's a natural operation on dicts unlike |
why isn't union a natural operation?
because there are two ways you can handle common keys
It feels very weird that they are adding intersection and union but not (symmetric) difference
I dreamed that global del was added as a compound keyword for forced garbage collection
that's the only python dream I remember tbh
I think I want to make a reddit thread to ask what forced garbage collection would entail. not because I think it's worth adding, I just wonder.
I think it's mostly a question of usability, what would be the purpose of manually setting the refcount of every variable to 0, you can just exit the program and run another
I don't think I understand what global del would do
I don't know a whole lot about how languages are implemented but I figured you might be able to have a special value that you get an error if you try to access. So if you force delete something that you would have used later, you get an exception rather than a segfault. And then references to that special value would have the same reference count as the object they replace
No please don't add js' undefined
no that's haskell undefined
@raven ridge the idea is that if you have global del x as a single statement, the object referred to by x is deleted before the next line is executed.
js undefined doesn't error
and anything it contains references to have its reference count decremented, and those objects are also deleted right away if the count reaches zero. Again, not saying they should add that, that's just the idea.
In addition to being terrible, that would be very slow.
@boreal umbra that sounds like it should be a function
What about objects that depend on x
like on gc or smth
I'm not sure I see the point, still
Every time someone does any operation on any value, the operation would need to first check if the value has been flagged as already-destroyed and raise an exception if so. On every single operation.
@teal yacht it would be the programmer's job to not mess it up. But I don't know if there's any way it could be implemented where you get an exception when trying to access a value you manually deleted.
So it's not really deleted?
In all cases where the user doesn't "screw it up", it would be equivalent to just del. The only case where it would be different is the case where other references exist and are now broken.
!e
thing = 'hello world'
my_list = [thing, 2]
del thing
print(my_list[0])
@boreal umbra :white_check_mark: Your eval job has completed with return code 0.
hello world
How would you access a value that doesn't have any binding to it
del thing doesn't delete 'hello world', it just removes thing as a name for that object.
Yes, and reduces the refcount of the object by one
Oh nice, built-in python execution
(modulo the fact that's its a literal string)
But if it did delete that object, then my_list would be broken
right
Which is bad.
I don't see the point
there isn't necessarily a point
We'll get disguised segfaults everywhere
I mean, you already can do this, if you want to see just how disastrous it winds up being. Use ctypes to change the reference count of an object to 1 before you del it.
Leaving existing, broken references to an already destroyed object is a very common bug in Python C extensions.
Letting people introduce the same bug in plain Python code seems exceptionally horrible
doesn't the Python api for C handle that as long as you use the decref function correctly?
or is that the problem?
Python C extensions are bae
doesn't the Python api for C handle that as long as you use the decref function correctly?
@boreal umbra right, the bug is keeping a reference to an object that you forget to incref. Or, alternatively, accidentally decref it twice.
Either way, when its reference count drops to 0 it will be destroyed, but its reference count is off by 1 from what it should be, and so something is still referring to it even though it's already been destroyed.
I should go to sleep so that my life is somewhat in harmony with my school schedule.
hey folks
if there is one book you had time to read on python
what would you go for
I personally quite liked "Automate the Boring Stuff" myself
Thought that was back when I was much more of a beginner
how many years back may I ask, @whole shore
man
I just checked it out
It looks like a fun read
any "python under the hood" kind of books?
Py_INCREF and Py_DECREF surely give me chills, haha
If you want to get the full dotted import path of a class is it safe and correct to do f'{theclass.__module__}.{theclass.__name__}?
There is __qualname__ iirc
Hmm so looking at it seems like to be robust it should be f'{theclass.__module__}.{theclass.__qualname__}?
That looks right to me. With the caveat that the full path to a module may not be the canonical path to it. That is, the class pkg._private_submodule.Klass may be reexported from pkg, so that users are meant to do pkg.Klass, and this approach would find pkg._private_submodule.Klass
Which isn't incorrect, but isn't exactly correct either.
Also with the caveat that I'm not sure __module__ is always defined. It appears to be writable for user defined classes, so someone could set it to something incorrect. I'm not sure if it's guaranteed to be set at all for classes defined in extension modules
So basically what I want to do is determine the dot-path of a class from within that class. The next part of this is I quite want to define it on a baseclass and then have it work properly for any subclasses defined elsewhere (i.e. return the dotpath of the subclass) - but I think that's potentially difficult?
That should work exactly the same way. The subclass has its own __module__ and __qualname__, so if you create a method that accesses self.__module__ and self.__qualname__, it will return the appropriate path for objects of whichever type self is, whether base class or subclass
Ok, that's pretty much what I thought I'd have to do. Since this doesn't actually require instance level values I was hoping I might be able to create something at the class level? Is there such a thing as a classproperty?
No, though you could make one if you were really determined. The descriptor protocol should allow that, I believe.
Meh a classmethod is basically fine I was just being picky
Is there anyone here who knows a lot about python that could be a mentor and help me it on my beginner level ?
Head to #python-discussion or #❓|how-to-get-help , this channel is solely based on discussing about the language and not helping on any topics @ivory gorge
Is there any way to serialiaze/pickle a file that uses selenium?
Apparently multiprocessing with selenium is (almost?) not possible because it can't be serialized
https://medium.com/@daanyaalkapadia13/send-email-using-python-30fc1f203505?sk=3b8fa70bd633b73fd77d0e9a60f9cf61
Please go and check out my first article🗒️ on medium. It's the first time I am writing an article so your support will be appreciated🙌.
@unkempt rock This is not a help channel. Please see #❓|how-to-get-help.
@cinder vale This is not a help channel. Please see #❓|how-to-get-help.
when bytecodes reference TOS (top of stack), are they referencing the top item of the data stack of the top frame of the call stack?
or are they referencing the top frame itself?
@boreal umbra thanks!
You're welcome! What did I do?
if there is one book you had time to read on python
@stable cobalt Fluent Python
You're welcome! What did I do?
@boreal umbra thanks!! I'm going to get that right now
Ah
@stable cobalt we have some recommend books on our website and I'm pretty sure FP is one of them, if that makes you feel any more confident about purchasing it. However it was written when 3.4 was the latest version and a newer edition is coming out within the next year.
😭
I'm going to go skulk to genesis
like seriously, books like doubled in price
has to be brexit
is brexit the place in uk?
Is there a way to automatically run super().__init__() in the __init__ of some class which inherits from a class that requires this?
I'm building a library where people will need to make a custom class that inherits from mine and I don't want to bother them with having to use super().__init__() first every time they use it. I was wondering how to automate this.
It's how every other class will work, doing it automatically will just confuse people
Probably yes, with some meta class magic for example. But yea.. Don't do that.
you could probably hack something together with __init_subclass__ in that base class as well (by patching __init__ with a new function that calls the base init and the actual init). I'd be pretty flabbergasted if I were confronted with that, though.
@tropic magnet this channel is for discussion. Take a look at #❓|how-to-get-help so you can open a help session.
Whats the best module to use for proxies?
i've actually done this before, adding super().__init__ to subclasses
!e
from inspect import signature
from textwrap import dedent
def parse_signature(signature):
return str(signature)[1:-1].split(', ', 1)[1]
def additive_init(cls):
def __init_subclass__(cls):
def add_parent_init(init):
self_args = parse_signature(signature(init))
parent_args = parse_signature(signature(cls.__base__.__init__))
globals_ = {'init': init, 'cls':cls}
locals_ = {}
wrapper = f"""
def wrapper(self, {parent_args}, {self_args}):
super(cls, self).__init__({parent_args})
init(self, {self_args})
"""
exec(dedent(wrapper), globals_, locals_)
return locals_['wrapper']
cls.__init__ = add_parent_init(cls.__init__)
cls.__init_subclass__ = classmethod(__init_subclass__)
return cls
@additive_init
class Person:
def __init__(self, name):
self.name = name
class Cyborg(Person):
def __init__(self, version):
self.version = version
class Android(Cyborg):
def __init__(self, model):
self.model = model
print(signature(Android))
@deft pagoda :white_check_mark: Your eval job has completed with return code 0.
(name, version, model)
@radiant scroll
Hello,
I found this little explaining text on a python project and I wonder how it works:
clients never write anything to the disk - not even temporary files (zero IO system calls are made) because remote imports allow arbitrary code to be dynamically loaded into memory and directly imported into the currently running process
Anyone knows which module is used ?
@frozen abyss can you post a link to the project?
@paper echo
Found this text on this project: https://github.com/malwaredllc/byob
it looks like it's more than just a single module that enables that functionality, maybe more of a clever design than some specific module
this is quite an impressive project
so this is a little off topic it is java what does this mean
**** FAILED TO BIND TO PORT!
[13:36:00] [Server thread/WARN]: The exception was: java.net.BindException: Can't assign requested address
[13:36:00] [Server thread/WARN]: Perhaps a server is already running on that port?
[13:36:00] [Server thread/INFO]: Stopping server
[13:36:00] [Server thread/INFO]: Saving worlds
[13:36:00] [Server thread/ERROR]: Exception stopping the server
java.lang.NullPointerException: null
@unkempt rock this is a discussion channel, so Python questions would also be off-topic for this particular channel. We don't really have a platform to answer Java questions here, but you could join the Together Java discord.
@heady mauve top of data stack
thanks @sacred yew
I'm just now discovering how awesome dataclasses are, I recommend to all.
@swift imp that's actually really useful
@unkempt rock - It means there is already a Minecraft server running on that port, or you've selected a port that requires root access to bind to.
@swift imp If you like dataclasses, you can look into namedtuple and its awesome typed version -- typing.NamedTuple
it's like a frozen dataclass
(dataclasses can be frozen as well)
oh very interesting, I'm familiar with namedtuple but not the typed version
yeah, that can be useful if you want to build an ADT
from typing import NamedTuple, Union, Tuple, Callable
class Log(NamedTuple):
severity: int
location: Tuple[str, ...]
message: str
args: Tuple[Any, ...] = ()
class SpawnTask(NamedTuple):
client_uid: int
task_path: Tuple[str, ...]
task_uid: str
class GetTaskResult(NamedTuple):
task_uid: str
class GetConfigValue(NamedTuple):
key: str
Command = Union[Log, SpawnTask, GetTaskResult, GetConfigValues]
Command is an 'algebraic data type' because it's a sum of products
(int * Tuple[str, ...] * str * Tuple[Any, ...]) + (int * Tuple[str, ...] * str) + (str) + (str)
I'm super lost here, why on Earth does that __get__ not get entered??
class PullFrom(object):
def __init__(self, table:str):
print("storing table")
self.table = table
def __call__(self, *args):
print("storing column")
f, = args
self.column = f(self)
def __get__(self, instance, owner):
print(f"getting table name {self.table} and column name {self.column} to pull value from")
return
class Test(object):
@PullFrom("A")
def value(self):
return "foo"
storing table
storing column
>> t = Test()
>> t.value
As inspired by the current name of ot1, why exactly is eval so evil?
why are you inheriting from object? 🤔
I get that it can evaluate malicious code
well... that's it 🙂
what if the user can't change what's being evaled without editing the file?
and it's overkill for some things people use it for
if the user can't change whats being evaled, then why are you using eval in the first place
I've used it (or it might have been exec that I used) to create some dataclass instances that were written to a log file
since the __str__ of a dataclass is typically the constructor for that instance.
It seems like inheriting from object or not doesnt matter. Even if you don't do it, you still inherit from it.
unless you're on py2
you might want __call__ to return self at the end
@sacred yew it's used in namedtuple, I think
@boreal umbra why did you need exec/eval for that?
@deft pagoda hot damn, smarty-pants, I'm still trying to learn all this stuff .🙂
@spark magnet my program creates a lot of dataclass instances during its execution and I wanted to get some stats about what it outputs
hmm, i still don't see where the exec comes in
so the easiest way to do that was to just resurrect all the instances and count how many items appeared in various list comps.
I use exec quite a bit for code generators
it might have been eval that I used. I can't remember which does which.
unapologetic about it, cause i'm not about to build an ast and compile it -- yet
@swift imp __call__ returns None, so Test.value is None
exec is for statements, eval is for expressions
was probably eval then
It's a good idea to steer people hard away from exec and eval because both seem like really elegant solutions to lots of problems, but are actually Python injection attacks in disguise
ast.literal_eval might be more useful, I suppose?
@grave jolt ty ty
is that train sounds?
it's certainly not that exec and eval are never useful - they're still in the language for a reason, and they're the best solution to some problems. It's just that it's an order of magnitude or two easier to use them than it is to use them safely, and drilling in to people's heads that it's generally unsafe and only safe in specific exceptional circumstances is a good starting point.
I see many people use it to implement a calculator for some reason
gross
Maybe it's counterintuitive, but making a reverse polish notaiton calculator is much easier 😛
SQL injection attacks are still one of the most common types of attacks, and they're much easier to prevent than Python injection attacks are - there's usually just a "sanitize this input" function you can call on your database driver.
Lisp parser is also fun
https://paste.pythondiscord.com/icugubiyan.rb I did a normal parser for a calc as an example once
I knew it, you've been a ruby programmer all along
the main problem I have with exec/eval is that they're builtins in the global namespace
seems a bit of a bad decision to me
fair
what's the reason?
exec/eval shouldn't be in the global scope because they're almost never the best solution (like reduce?), and they create a security hole
id isn't harmful, it's just not very useful
as in, I agree that exec, eval and id all shouldn't be in the global namespace; the first two because they have the abovementioned pitfalls that new users won't be aware of, and id for the reason you gave
I like reduce...
😦
and the really irritating thing?
we have comprehensions, and map/filter, which are alternatives
but reduce, which has no alternative other than a loop, has to be imported
🥴
I wish there was a map that would return a list/tuple/string, not an iterator
there is, it's called list(map
lol
I think @grave jolt means like a method that returns an instance of the same class
yeah
like Scala has
Well, I would rather use a list comprehension than list ∘ map
scala> List(1, 2, 3).map(_.toString)
res0: List[String] = List(1, 2, 3)
scala> Vector(1, 2, 3).map(_.toString)
res1: scala.collection.immutable.Vector[String] = Vector(1, 2, 3)
I think you could easily look at Python's builtins and name 50% of them that shouldn't be in the builtin namespace easily.
I think you could easily look at Python's builtins and name 50% of them that shouldn't be in the builtin namespace easily.
@raven ridge I think we did that a month back or so
I have literally never used oct
id is bad, sure - but ord and chr have no business being builtin, and I've literally never used slice. memoryview is pretty rarely used... help is only used in a repl and could be handled like quit is...
TIL that ascii exists 😄
slice and memoryview should be in some library like extra_builtin_types.py, maybe frozenset as well
I would like it if frozenset got the f-string treatment
f{1, 2, 3}
also not really sure about basic math functions like abs being part of global namespace
...maybe just add those things in types and rename it?
I think it's an interesting design choice
not clearly bad, but it might surprise some people
because these things aren't part of the global namespace in most languages
callable was removed and then added back. 😦
I've literally never used complex, either.
stay away from complex, mate
i didn't understand why callable was removed. They said, "If you want to know if it's callable, just call it" which seemed really naive.
uh... yeah
complex is my built-in 2-vec class
well, we do have inspect, though
i didn't understand why callable was removed. They said, "If you want to know if it's callable, just call it" which seemed really naive.
@spark magnet sounds quite EAFP
"Hey, there's this funny do_segfault object, let's poke it and see if it's callable"
it does, but sometimes you need to know without actually calling it
yeah, precisely
Well, checking if it has __call__ might be ok
exec/evalshouldn't be in the global scope because they're almost never the best solution (likereduce?), and they create a security hole
idisn't harmful, it's just not very useful
@grave jolt what's wrong with reduce?
one of the cases where the EAFP idea breaks down
note that it's not possible to check if a class has an attribute without fetching that attribute.
hasattr calls getattr and swallows the AttributeError.
@boreal umbra Well, it goes in the same place as the other things like memoryview and id and slice. They can be useful, but not in the global namespace
I thought reduce was in functools
Yes, it is
I thought reduce was in functools
@boreal umbra it is
that's the problem
why? 😡
i've used slice enough
I've only used reduce to chain __or__ calls
@gleaming rover I think I used it reduce very few times. Can you show examples of where it's better than a loop?
slices are neat when you abuse them for things they aren't meant for
don't think it's ever better per se...?
@raven ridge Well... that makes sense, kind of. Because many magical proxies/frameworks/etc. use __getattr__/__getattibute__
But maybe __hasattr__/__hasattribute__ could be a thing as well?..
but it is more concise
and generally fits better with the way I think
I just don't really like loops
Maybe I'm just too used to loops
or rather, I don't like loops when there aren't side effects
which is a bit of me being a purist but well
like I think I go quite out of the way not to rebind variable names
well, if the function already exists, it could be better
I do agree that reduce is generally less comprehensible for the average person than loops
like I think I go quite out of the way not to rebind variable names
I think I'm the opposite, I greatly enjoy rebinding variables, almost whenever I can.
can you use just one variable name for the entire program?
no, this is getting #esoteric-python
mypy drives me crazy by assuming that a variable is only gonna have one type, heh
@raven ridge does it assume that you're never going to reassign instance.__class__?
I mean, other people do need to maintain my code 😄
but I don't think twice about doing things like
if not isinstance(name, str):
name = name.decode()
and mypy doesn't like that at all.
anybody knw how to downlaod libraries in python
pip install (library name)
I'm trying to retrieve my ip address in Sockets SERVER = socket.gethostbyname(socket.gethostname()) but its throwing the local ip 127.0.1.1
please ping me if anyone knows what I'm doing wrong
Hey there! is there anyone who is able to help me out on my assignment? I have some questions and doubts I wanted to ask for my assignment
shoot me a Private message because I really need help and hopefully i can get going from there
@elder hawk Hello, just a fair reminder that this is not a help channel. Feel free to check out #❓|how-to-get-help though.
ok
This is not a help channel, if you need help with python you'd be better to check #❓|how-to-get-help
Also keep in mind pretty much any music service prohibits automation of their services. @scenic flare
@unkempt rock This is not a help channel.
@gloomy rain I didn't ask for help
I was just saying that
Also keep in mind pretty much any music service prohibits automation of their services.
this is not true
Which is still not the topic of this channel.
okay if my two lines made the whole discussion off-topic I am sorry.
Do not continue or prolong off-topic conversations. Thank you.
Is dataclass a type of metaclass?
There may be some meta in how it works, but the dataclass decorator calls a function that does the magic
Looks like they got rid of the only metaclass usage a while ago because class getitem came around. The function works directly on the current cls object with modifying its attributes https://github.com/python/cpython/blob/master/Lib/dataclasses.py#L809
I think I'm the opposite, I greatly enjoy rebinding variables, almost whenever I can.
@raven ridge why, though?
my PoV is that a name should have a consistent meaning while it's in scope
and if it's rebound, then that's not true
Hi, i have a question in Cpython 3.8 api.
i am trying to do the same thing as
vars(str)
``` but in C. the equivalent of `vars()` in Cpython-api is `PyModule_GetDict`, and the equivalent of `str` in Cpython-api is `PyUnicode_Type`.
So i thought that i should do `PyModule_GetDict(PyUnicode_Type)` , but that doesn't work because `PyModule_GetDict` should get `PyObject` as its parameter and `PyUnicode_Type` isn't `PyObject`, it's `PyUnicode_Type`
i am getting that error:
```python
SystemError: Objects/moduleobject.c:477: bad argument to internal function```
i will be happy to have some help, Thanks.
@raven ridge why, though?
@gleaming rover because when something semantically represents the same piece of data in a different format, I prefer using the same name. Given the choice between:
def execute(query):
if isinstance(query, bytes):
query_bytes = query
else:
query_bytes = query.encode()
And:
def execute(query):
if not isinstance(query, bytes):
query = query.encode()
I much prefer the latter
@soft bone PyModule_GetDict requires a module, not just any Python object, and str/PyUnicode_Type is a type, not a module
@soft bone
PyModule_GetDictrequires a module, not just any Python object, and str/PyUnicode_Typeis a type, not a module
@raven ridge so how can i do vars(str) in c-api? can you please send me a link or something to take a look at?
@soft bone PyObject_Dir((PyObject*)&PyUnicodeType) should do the trick, I think
@soft bone
PyObject_Dir((PyObject*)&PyUnicodeType)should do the trick, I think
@raven ridge Thank you, apreaciating!
what is the default metaclass for user-defined types? do int, str, dict, and list each have their own metaclass since they each have their own built-in syntax?
The type of the builtin classes is type, so that should be their metaclass; same with an user defined class where you don't specify it
They don't really need metaclasses since you can do much more at the C level
so are there any stdlib examples of a non-type metaclass?
enums use metaclasses extensively for example
!e
class A: pass
thing = 'hello world'
thing.__class__ = A
@boreal umbra :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | TypeError: __class__ assignment only supported for heap types or ModuleType subclasses
so A and str share the same metaclass, but I guess user-defined types belong to "heap types"?
I believe you'd get the same error with an instance of A
maybe if you try to replace an A instance's class with str but it does work in general.
!e
class A: pass
thing = A()
thing.__class__ = str
@boreal umbra :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | TypeError: __class__ assignment only supported for heap types or ModuleType subclasses
IDK if it's advanced, but what is my error? The terminal doesn't show nothing, but the bot isn't removing the roles. [discord.py]
@client.command()
async def det(ctx, member: discord.Member, role: discord.Role):
print(member)
print(role)
roles = [r.name for r in member.roles]
r_testadores = discord.utils.get(member.guild.roles, name = 'testadores')
r_da = discord.utils.get(member.guild.roles, name = 'Da')
r_db = discord.utils.get(member.guild.roles, name = 'Db')
r_dc = discord.utils.get(member.guild.roles, name = 'Dc')
r_dd = discord.utils.get(member.guild.roles, name = 'Dd')
if r_testadores in roles:
await member.remove_roles(r_testadores)
if r_da in roles:
await member.remove_roles(r_da)
if r_db in roles:
await member.remove_roles(r_db)
if r_dc in roles:
await member.remove_roles(r_dc)
if r_dd in roles:
await member.remove_roles(r_dd)
await member.add_roles(role)```
After looking around, yeah it does look like a heap type refers to a class that was defined with the class statement (and type I guess) in python
@unkempt rock I don't know the library, but it looks like roles is a list of role names, instead of the actual roles.
@unkempt rock I don't know the library, but it looks like
rolesis a list of role names, instead of the actual roles.
@zenith topaz yes! roles give me the roles name.
It doesn't really fit in this channel though you can open a help channel in #❓|how-to-get-help or use the #discord-bots channel
It doesn't really fit in this channel though you can open a help channel in #❓|how-to-get-help or use the #discord-bots channel
@zenith topaz Ohhh, thx!
Hello has anyone tried DataCamp or DataQuest?
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
@boreal umbra Those are just python-language oriented
The things I linked are career/skill oriented, such as using python with pandas, matplotlib, tensorflow, sql and so-on to do computer science, math and data science etc
you could ask in #career-advice how people got the training for the jobs they have, I suppose.
Heyg
I think this channel is not that active
So I wanna ask something so reply to me personally or something
Or jus reply here fast or something
So is there a code to convert IP to CO ordinate?
Longitude and latitude
@unkempt rock if you ever want to know if there's a python package for something, check the Python Package Index (PyPI--which is always pronounced "pie pee eye" and not "pie pie"). Be sure to read the topic for different channels because we always want to stick to them (especially this one) even if an on-topic discussion isn't ongoing.
Oh ok
@unkempt rock There are APIs for that I believe
A quick Google search returned this for example: https://ip-api.com/
Free IP Geolocation API - lookup any IP address
Also just an fyi, you won't get absolute cords with any IP service, most they'll give you is the cords of the city the IP is located in, for privacy reasons, plus the ISP of said IP only really knows exactly where that IP is located at any given time
Can you define __eq__ on a dataclass and still have it create __hash__ for you automatically? I can't tell from the description at all
For it to generate __hash__ you need frozen=True and eq=True but if you define a custom __eq__ then eq arg is ignored so like
What does that mean wrt to __hash__
It's not possible, if it does generate it for you, it's a bug
because there's no way to know what the eq function does to create the hash automatically while keeping the property if x == y: hash(x) == hash(y)
So I'd have to implement __hash__ myself
Hi, not sure if this is the right place to ask, but is anyone here familiar with pybind11? I'm working on a project that uses python and c++.
@late jay #c-extensions would be better
Awesome - thanks!
@swift imp if any member variable used by __eq__ can be changed, it shouldn't be hashable at all. Otherwise, you'll need to define you own __hash__ based only on the fields you included in __eq__, being careful to preserve the invariant that object equality implies hash equality
@unkempt rock #tools-and-devops would be the channel to discuss that.
is there a good way to parse parts of a file as a CSV file?
@hot oracle you could use regular expressions to parse out the parts that you want and send them over to pandas.
if you have any more questions about that, I'd check out #❓|how-to-get-help
as in, there's a specific topical chat I should ask in, or I should use what's described there to get my question asked in one of the open help channels?
the latter, though #data-science-and-ml would be the most relevant topical channel if you wanted to go the pandas route.
Anyone else that enjoys reading the PEPs? :)
someone must
@wet obsidian what is your favorite pep?
I like the pattern matching PEP but I'd rather have null-aware operators in the meantime
It's an old PEP that was deferred
I'm still looking as to why, but I asssume it's indefinite
On top of my head, I often do
if car and car.fast: car.brake
which could be replaced by
if car?.fast: car.brake i think? hope I understood it well
In particular I don't like the first form, because I feel like it's sorta counter-intuitive because it's "abusing" short circuit evaluation
@wet obsidian how is it abusing? Isn't it exactly what short-circuiting is for?
Dunno...? Figured it was for performance or something?
but since we're talking Python here, you're probably right lmao
I mean it's more of a
# Coalescense (roughly)
if a is None:
return b
else:
return None
# Maybe access
if hasattr(obj, "attr"):
return obj.attr
else:
return None
hmmm?
or I misunderstood coalescense
Still, having short-circuting attribute access is fairly neat
For sure
It's just not very consistent with other operators
and sorta adds an extra layer of complexity:" what's gonna get evaluated and what won't"
I'm nitpicking ofc
Also.... if they didn't short circuit, is it possible we could overload them?

there's a dunder proposed i think at the bottom of the pep
i don't remember what it was
sorry, I meant the or and and ones
I played with attribute chaining not long ago, it's not difficult to implement a version https://github.com/salt-die/Snippets/blob/master/maybe.py
In Haskell there exists the Maybe datatype (e.g. Option in Rust if you're familiar) that basically allows you to short-circuit evaluation
getInfractionMessage = do
infraction <- getInfraction 42 infractions -- If this fails
reason <- getMessage infraction -- this never runs
return message -- nor does this
I mean, it's useful for a language like Haskell because it can be repesented in an abstract manner plus you don't really want exceptions in the first place; there's also the fact that there's a million other combinator functions that you can compose
A special mapping type that can do a great job at error reporting might be a better candidate for the task to be honest
wouldn't be hard to add error reporting to the class above, but it's maybe unweild-y, I dunno -- it was more academic
Maybe something like:
try:
Maybe(infractions)[42]["reason"]
except MaybeKeyError as e:
print(f"Failed to access {e.last} at {e.depth} depth.")
```?
i mean, sort of the point is that you don't have to catch errors though
Hm, fair
also to avoid the nested elifs when checking deep
To be honest I don't really see features like pattern matching or none-aware operators making it to the language in the near future e.g. 3.10, 3.11
probably not, i think pattern matching is too controversial --- though I'm really not sure why none-aware has been deferred so long
pattern matching was approved though? Whoever we've enslaved to work on python just needs to work faster
PEP 622 is still a draft but there's an implementation
switch case itself could be revisited at some later time, if it ever became more popular
Was the walrus operator really the reason why GvR stepped down as BDFL?
PEP 622 is still a draft but there's an implementation
oh my bad, dunno how I got it mixed up
or it's just some tall tale
probably scored a job at google
why is it so bad?
It's alright but I really do underuse it
I'd like to keep compatibility with 3.7 as much as possible
Some packages that I'm currently writing I'll go and publish to PyPI
PyPI doesn't work with 3.8?
i'd love a none-aware operator, but i probably wouldn't use it very much in Python
No, I just like having packages be compatible with a previous release, especially if they're tools
i haven't ran into many situations where you chain lots of function calls
Cries in fluent interface
tbh, all the low hanging fruit is probably already taken. Hard to come up with new stuff
No, I just like having packages be compatible with a previous release, especially if they're tools
Okay, I see
RegExp literals 
no
that still looks like a string literal
and the whole point is that regex literals aren't strings
just use slashes like other langs
does this question belong here
@livid mason you can ask questions in this channel if they're meant to spur discussion about the design of the language. Most questions belong in a help channel.
okay thank
Hey guys, I'm trying to move away from pipenv. But I do like the virtual environment setup.
I was wondering if pip-tools + venv will work about the same way as pipenv?
@prisma cypress I've only ever used venv. In what way do you feel that it's lacking?
I remember coming across with pipenv having issues installing packages.
I've also read that pipenv stopped development. I figured I might as well take the opportunity to try something new.
Though to be fair, I think the issues while installing packages were from pipenv dependencies instead of pipenv itself.
Oh I've never used venv before. hahaha
Do you have a question about how to use it?
I'll probably try it out myself later and if I have further questions I'll come back.
I was just wondering about the ease of use and what managing venvs are like.
Such as listing the virtual environments.
lister = ["hey", ["hello", "hi"]]
for word,the_list in lister:
print(word)
print(the_list)``` error: ```py
for word,the_list in lister:
ValueError: too many values to unpack (expected 2)``` why doesnt the library allow me to iterate through a sting and a list within a list?
any alternatives to this?
You can do nested loop.
@livid mason that question isn't on topic for this channel. You can use a nested for loop though.
can u give me links to what nested loop is? thanks, i wont post q like this again here
for string in lister:
For char in string:
Do stuff
can u give me links to what nested loop is? thanks, i wont post q like this again here
@livid mason it's something you can easily Google IMO
I'm on my phone so I can't do better than that.
@prisma cypress one trick with virtual environments is that you can't move them, I don't think
They manifest as a directory with a few sub directories, one of which has the python executable.
@tawdry gulch every value in a list has to be a tuple of the same length for unpacking to work.
@tawdry gulch every value in a list has to be a tuple of the same length for unpacking to work.
@boreal umbra every value in an iterable has to be an iterable of the same length, but yes
Oh, yeah, my bad I am being stupid
For some reason I thought he was trying to unpack the list itself, woops
it would work if it was lister = [['hey', ['hello', 'hi']]]; the loop would run for one iteration with word = 'hey' and the_list = ['hello', 'hi']
I'm in bed with one eye open, don't at me.
Ahh okay okay. Thanks Stelercus.
From what I've gathered, it seems like just manually dealing with the venv instead of the automating part from pipenv.
I think I can deal with it.
My other option was using poetry.
Pipenv is pretty much dead too.
I stick with just using venv over conda and such because if I run into an environment related issue, the solution will probably assume I'm using a virtual environment.
And I don't want to have to think about if another thing like that is going to affect the applicability of an online answer
Because how else am I going to code?
Staying on the beaten path is a good default, unless you have strong reason to be out in the woods :)
Now I'm thinking of lost in the woods from frozen two. I liked that movie.
Another limitation of venv that I can think of is that you can't upgrade python versions, I don't think
Quick question about venv. I can have the directory made first and then linking the virtual environment to it right?
Let's say I pull from github.
Oh as in you can't upgrade the python version after the virtual env is made?
Ahh okay okay.
Also you don't want the virtual environment in github or in a git repo
It would be part of your git ignore
Ahh. Where would you recommend setting up the virtual environments?
If you're making an installable package, you would have the dependencies in the setup file
And you would install the package in editable mode
Otherwise you have a requirements file
Which is just a text file that lists the dependencies
You can't upgrade python and keep your installed packages without venv either, so no difference there.
And pip can automatically install everything listed in a file with the -r flag
Ahh. Where would you recommend setting up the virtual environments?
@prisma cypress virtual environment generally live in the top folder of the project they serve
They just aren't checked into git
To clarify, then we do add it to git ignore?
Git ignore templates for python projects will always have venv
Oh! Ty ty.
I've tried out venv thus far, more typing. As such with source .../bin/activate.
But it seems pretty smooth.
To remove the venv, can I just delete it?
Yes
cool cool cool.
I think it'll be alright if it lives at the top of the project folder.
Nope, thank you so much! Right now I have to shop for a router because a friend's router is dying.
It's not much typing if you use a good shell that auto completes for you. I recommend fish.
Aliases are also useful. I have vv bound to source .venv/bin/activate and vvv to python3 -m venv .venv && [[ -f requirements.txt ]] && pip install -r requirements.txt
or use autocomplete feature of zsh shell
i need help
File "main.py", line 1, in <module>
from imageai.Prediction.Custom import ModelTraining
File "C:\Users\arnav\AppData\Roaming\Python\Python37\site-packages\imageai\Prediction\Custom\__init__.py", line 4, in <module>
from ..DenseNet.densenet import DenseNetImageNet121
File "C:\Users\arnav\AppData\Roaming\Python\Python37\site-packages\imageai\Prediction\DenseNet\densenet.py", line 21, in <module>
from tensorflow.python.keras.utils import convert_all_kernels_in_model
ImportError: cannot import name 'convert_all_kernels_in_model' from 'tensorflow.python.keras.utils' (C:\Users\arnav\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\utils\__init__.py)
error
@cinder nacelle This is not a help channel, this is a discussion channel, see the description. For help, check out #❓|how-to-get-help
@pallid crescent Let's not post that here
Hi
@unkempt rock This is not a help channel. Please see #❓|how-to-get-help.
@prisma cypress actually, you can upgrade a venv after it's been created, but it's often just as easy to create a new one in the same project folder and re-apply the requirements.
hello,
Anyone knows how to execute code after having compiled a python program in bin ?
thanks in advance
How much is Python influenced by Smalltalk?
I'm working through the GNU Smalltalk tutorial, and I am sensing some slight similarities.
Like, for example, classes (which are objects as well) have a new class method, which is responsible for making a new instance, and instances have an init method which is called by new.
Object subclass: #Account
instanceVariableNames: 'balance'
classVariableNames: ''
poolDictionaries: '' !
Account comment: 'I represent a place to deposit and withdraw money' !
!Account class methodsFor: 'instance creation'!
new
| r |
r := super new.
r init.
^r
!!
!Account methodsFor: 'instance initialization'!
init
balance := 0
!!
Hi ! Has anyone here worked on GIS maps ... like NASA Earth data in Python ?
I have a few questions regarding it ...
@wispy holly This is not a help channel, it's a discussion channel. See #❓|how-to-get-help
and I am sensing some slight similarities.
Dunno, I'm "sensing some slight similarities" between all languages lmao
Well, C and Python don't have many similarities 🤔
I mean, compared to haskell they do
Perhaps
@grave jolt this code looks like ruby to me
Any structural advice for basically wrapping an external api, one that requires a lot of config options (basicly handles all interaction with a google static maps api) and basically it needs around 5 mandatory args, and around 15 optional ones, im having trouble deciding between some kind of enums for specific optional param choices or just sticking everything in kwargs?
for the latter a pattern has emerged, there's gotta be a better way...
if kwargs.get('optional_param'):
do something()
else:
something_else()
Any suggestions?
Also sorry if it's not the right channel, perhaps more of a software design question
@brazen jacinth I suppose it's on topic in the sense that it's "how can I use the language most expressively?"--if you're using repl.it, remember to change the settings to be four spaces per indent.
can anyone tell me how discord python bot works?
just a pasting issue ;P
@manic hatch are you asking how our bot works, or how to use the discord api for Python? We have a channel to discuss the discord api, it's #discord-bots
i want to use this python bot in other apps
@brazen jacinth you could use early exiting
not sure what exactly that is, but the problem is, this function is being used by cca 30 other functions, and has grown out of bounds to be used in many ways, so i would kinda like to retain "backwards-compatibility" by checking for all the arguments to still retain support for all these functions
@brazen jacinth how about 'optional param' in kwargs?
can anyone address my question?
that would work in general, but would have to refactor all of those functions in order to make it work, but yea, if i started anew that would seem like a good choice
im gueesing the fact that i have to retain this compatibility (or simply bite the bullet and refactor now), it makes things a bit more..difficult annoying
@manic hatch here is the source code for the bot: https://github.com/python-discord/bot
You would need to adopt it for your server and deploy it, as it is only designed to work on this server.
Hello, is anyone here good with django or http requests and routing?
you'll have more luck in #web-development
thanks
Ty ty @boreal umbra
another pattern I've seen is is bib = whargs.pop("bob") -- to check whether there are unprocessed kwargs (in order to throw an error)
thanks, that popped some ideas actually
@brazen jacinth I've written about someething that sounds very similar: https://kodare.net/2020/09/14/transparent_apis.html
I might have explained it badly though, so feel free to tell me you don't understand at all what I'm on about :)
Is it possible to communicate with a printer by sending it an http request of some sort?
I see that my printer appears on my print queue for notepad with the location 'http://192.168..:***' (I added the stars), so I wonder if Windows just uses http to print to wifi printers.
@heady mauve no need to censor that ip by the way, it's a private ip.
ok thx guys
Re: boxed. Seem interesting, but yeah, I at least didn't catch the final part >_>
]
Why does true multi-threading not exist in python
I'd assume because of the GIL
The what? excuse my stupidity 😅
The GIL is the global interpreter lock, if I remember correctly, it makes sure that only one threads steps through Python code at a time
why do we need the GIL? i heard one of the reasons was to keep reference counts accurate?
well, you don't need it, but if you remove it you have to put locks everywhere and python gets even slower
"true multithreading" isn't a very precise term, anyway.
i imagine at some point far in the future python will be multi-threaded naturally
probably when having infinite locks doesn't outweigh the gains from running on 100 cores
or something
or someone figures something more clever out
"Python" the language doesn't have a GIL, necessarily. CPython the reference implementation of the language does, but it's an implementation detail. CPython does have "true multithreading" in the sense that it is possible to run code in multiple operating system threads.
well, yes
What's not possible in CPython is having multiple threads executing Python bytecode or manipulating Python objects simultaneously.
you can still use multiprocessing and universal queues
though, i haven't found many use cases for it -- but I don't do a lot of concurrent programming
and, things like numpy can often release the GIL while they do their stuff.
"true multithreading doesn't exist in Python" is only true if you make up a definition for "true multithreading" on the fly. There's a lot more nuance to the story.
you ever seen this: https://github.com/dabeaz/curio/blob/master/curio/queue.py#L81
he has talk somewhere where he uses threading and async together using these queues
It's a clever design, but I'm trying to wrap my head around the use case for it - presumably it's to make it so that the producer doesn't have to know where or how the consumer is running (or vice versa, perhaps) - but how often do you change your concurrency model? Is it often enough to go through the overhead and extra abstraction of using a different queue library right from the start to enable the flexibility to switch later?
maybe, I think the nice thing about these Queues is the abstraction isn't really that deep, it's not too hard to grok the entire curio codebase really -- makes it way nicer than trying to learn async from scratch, say
I mean, I get that it's a pretty thin abstraction, but you need to know that you want that abstraction from the start, or you need to always use this queue whenever you would use any queue...
it's probably pretty easy to just use it as a drop in whenever you need it
#❓|how-to-get-help @manic hatch
#help-candy is the channel. Join me if you can guide me with bs4
eh - it's got a consistent interface for all concurrency models, but that interface is different from all the standard queues. it's not API compatible with a queue.Queue - and if you need to make changes to your code to switch away from queue.Queue to something else, you could just as easily switch to multiprocessing.Queue as curio.UniversalQueue
is it that different? it's got a get and a put
it lacks options and knobs that you can twiddle for a queue.Queue, but fair enough that if all you need is a blocking get and put, it could just be swapped in
I haven't used that library in ages, and it's off-topic for this channel.
@manic hatch please don't keep asking in here - it's off topic. Be patient with your help channel, everyone here is a volunteer giving up their time freely. If it goes unanswered you can try asking again at a later time, when someone else who can help might see it.
Can Python benefit from branchless programming?
Basically, no.
if you need to use hacks like that just write it in c/c++
Why can't Python benefit from branchless?
Because the interpreter itself needs to branch a lot in the process of executing your code.
Avoiding branches in your Python code likely actually means performing more CPU branches, because avoiding branches in your Python code generally means executing more bytecode instructions, and executing more bytecode instructions requires more CPU branches in the interpreter.
This is a cool idea, but I’m not sure if it feels really pythonic, what do ya’ll think? https://mail.python.org/archives/list/python-ideas@python.org/thread/QAU3URTLBVZDQA7TWECUXCG6FENRR7VZ/
Unpythonic. What if replace is also defined?
I'm not really sure to be honest,
x = "foo"
x .= upper()
```feels unintuitive as I personally mentally parse `upper()` not as a method of `x` but a separate function.
def foo():
pass
x .= foo()
Exactly.
This will have the IMO surprising effect that those two foo() s are unrelated
Yeah, that’s a good point
https://del.dog/psutilerr
Why try execpt block is not catching error while importing psutil ?
Python 3.8.5 (default, Jul 24 2020, 12:38:30)
[Clang 9.0.8 (https://android.googlesource.com/toolcha
The bigger issue imo is what would foo.=6 do
@flat gazelle foo = getattr(foo, "6") ?
Force-casting the value to a string before the attribute lookup?
Why force-casting? foo .= bar also "force-casts" the identifier bar into the string "bar" when doing foo = getattr(foo, "bar")
6 is not an identifier though
So? My point was: whether it's an identifier, or a number, or whatever, it always gets converted into a string.
Attributes are always strings
foo .= bar isn't foo = getattr(foo, bar)
i don't find it too unintuitive, but I can't think of much use for it either
It's passable I guess in cases like string .= upper(), but IMO it's really, really iffy
I don't think the convenience is worth the questions it starts
i just can't think of any time i've ever wanted the convenience
i'm trying to think of one
String manipulation is the only thing I can come up with
Raku does have it, Nim too most likely
would that be a new dunder
I could see it as an alternative to the . operator, but then it has to be an expression like :=
__igetattr__
Returning a function from that to make a.=b() work sounds not great
And, well, what about every other operator, such as a.=b[0]
What about a []= 0 , meaning a = a[0] ? 😄
That I would be more ok with, since you put an expression into getitem anyway
Would conflict with the kwargs in getitem pep, but whatever
But at the same time, that happens rarely
But then we'd also need a ()= foo, bar=23 , meaning a = a(foo, bar=23)
That seems utterly useless tbh.
@unkempt rock This is not a help channel. Please see #❓|how-to-get-help.
Hey everybody, I am trying to advance my knowledge on metaclasses and actual usage of them, could somebody point me to an actual project that has used metaclasses properly and extensively so I can do a little reading/inspecting on it ? 🙂
Django?
I am not very familiar with Django it self so I find it a bit hard to understand what's going on there exactly
but yeah, guess I will have to stick with it for a bit ^^
I think SQLAlchemy also uses them for declarative models, that might be a bit easier to understand, if that is a thing when it comes to metaclasses 🙂
Oh, awesome, SQLAlchemy is thing I have some experience with, not very extensive, but at least some
Thanks a lot! ❤️
It feels like with every release of Python metaclasses are needed less and less. Most things can be done with class decorators or new dunder methods nowadays..
I am just interested in understanding them, I really see no reason of using them except for maybe Singleton implementation, but just want to get the hang of them, for my own sake 🙂
is stating that an input value requires __iter__ a way of saying that it's fine to pass a list, a tuple, a dictionary ( just the keys will be used ), or not. I feel like these can often be used for the same purpose - ie, iterating over them and carrying out some process. I'm not sure what would go wrong by enforcing that the input type has __iter__ instead of using isinstance( obj, (list, tuple, dict))
__iter__ would allow for iterables to be passed so that's that, if you have a way to manage infinite collections on whatever procedure you're running then not much would go wrong.
so i guess using hasattr(obj , "__iter__") vs isinstance( obj, (tuple, list, dict)) 🤔
you can use typing.Iterable
>>> from typing import Iterable
>>>
>>> isinstance([], Iterable)
True
>>> isinstance((), Iterable)
True
>>> isinstance({}, Iterable)
True
>>> isinstance(123, Iterable)
False
i don't use typing at all 😬

>>> from collections.abc import Iterable
>>> isinstance(obj, Iterable)
But yeah, the re-exports from typing are nice
they're making it more straightforward in 3.9 aren't they ?
maybe I'll jump on then
PEP 585: Builtin Generic Types
In type annotations you can now use built-in collection types such as list and dict as generic types instead of importing the corresponding capitalized types (e.g. List or Dict) from typing. Some other types in the standard library are also now generic, for example queue.Queue.
that's it, i guess
It's pretty neat
right - as i understand it'll be more straightforward from 3.9, and save me doing things twice if i wait a bit
i might just be being lazy tho and looking for excuses
the docs mention a caveat with __getitem__: https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable
well I think the best way to express that is to annotate that param as typing.Iterable, at least that's the way I'd approach it
if someone decides to pass a non-iterable, let it fail 🤷♂️
and you'll do that after 3.9 as well?
Iterable is an abc
I'm not sure if 3.9 changes anything w.r.t. that
you no longer have to import typing.List to annotate something as List[int]
you can just do list[int]
yeah , maybe that's all there is 😄
@gusty relic This is not a help channel. See #❓|how-to-get-help.
plz help me at #help-apple I need more advanced ppl
muted?
!mute 453358610953535500 12h The message literally right above is telling you that this is not a help channel. When you come back, stop blatantly disregarding staff instructions.
:incoming_envelope: :ok_hand: applied mute to @south token until 2020-10-02 01:06 (11 hours and 59 minutes).
you can use
typing.Iterable
@sacred tinsel I thought nothing intypinghad any effect at runtime
but you're saying that it works for isinstance?
!e
import typing as t
my_type = t.List[int]
my_list = [1, 2, 4]
print(isinstance(my_list, my_type))
@boreal umbra :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | File "/usr/local/lib/python3.8/typing.py", line 766, in __instancecheck__
004 | return self.__subclasscheck__(type(obj))
005 | File "/usr/local/lib/python3.8/typing.py", line 774, in __subclasscheck__
006 | raise TypeError("Subscripted generics cannot be used with"
007 | TypeError: Subscripted generics cannot be used with class and instance checks
guess it's only "compound" types.
that wont work, you can't use isinstance with typed generics afaik
ig its cuz its very costly to evaluate as data strucutes like lists can contain any (and a mix) of types, so it would need to look at every item in that container
it should be up to the programmer if they think it's worth spending computation time on that.
i think it would be nice if it could evaluate generators through isinstance by their return annotation (if it has one), so for example py isinstance(itertools.count(), typing.Iterable[int])would return true (assuming itertools.count() has annotations saying that it will return int only
its not fool proof, you could lie about the types returned but I feel for the most part that could be nice in some cases
but that wouldn't work for infinite iterators like itertools.count(), it can't evaluate every item
if thats what you mean
the /s is for "end sarcasm" 😄
but that wouldn't work for infinite iterators like
itertools.count(), it can't evaluate every item
just run it in parallel
/s
it can’t and shouldn’t evaluate iterators at all
Okay a weird question, not sure if #internals-and-peps or #esoteric-python — has anyone ever heard about any project that can connect several python files (say, in a package) into one?
wrong channel
Hello, I'm looking for a feedback based on experience regarding ML forecasting technics issues in training the model in a small sample size and moving it to whole set of data, for example take a small sample of data that is very representative of the whole set test different models select one then go to the selected model train it in the whole set of data to see if that's the right model to use for our data ? will this be a correct approach ?
@proper remnant please read the description of channels before posting.
but you're saying that it works for
isinstance?
@boreal umbraisinstance(x, typing.Iterable)works yea, but it cannot be parametrized with the subscript
but unless you need to branch based off whether something is iterable or not (or a similar use case), it's probably better to not do the check
if you try to iterate over something that is not iterable, you already get a very nice type error out of it
so it should be considered whether raising your own type error even adds anything of value
@unkempt rock Yes that will be a good method. If your original dataset is very large or you have limited computation power.
Random Sampling generally works fine in most cases but if your dataset is special like Time Series then random sampling is not a good choice.
Otherwise if you do a good sampling you should be able to get a good model.
on the other hand, if you have a function that is annotated to take a e.g. a list but can in fact take any iterable (I find that's often the case), you may want to consider relaxing the annotation
@unkempt rock that would be a question for #data-science-and-ml
so how does it know if something is iterable? hasattr(x, '__iter__')?
I also try to use t.Iterator any time it doesn't have to be a list.
sorry, iterable
That wouldn't work
You can create an iterable object if the class just implements __getitem__
!e
class MyIterable:
def __init__(self, data):
self.data = data
def __getitem__(self, i):
return self.data[i]
for i in MyIterable([1, 2, 3]):
print(i)
@wide shuttle :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
In this case, it relies on the first item being able to be fetched using 0 and it raising an IndexError when you run out of items. (I think StopIteration would also work.)
I don't like that
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
return _check_methods(C, "__iter__")
return NotImplemented```
def _check_methods(C, *methods):
mro = C.__mro__
for method in methods:
for B in mro:
if method in B.__dict__:
if B.__dict__[method] is None:
return NotImplemented
break
else:
return NotImplemented
return True```
This is sometimes referred to as the "old" iteration protocol
glad that it's old
I think the docs somewhere say that just trying iter(object) is the best way to see if something is iterable
I guess if you really need to check, you could:
>>> try:
... iter(x)
... except TypeError:
... ...
yea I think the docs recommend it
The only reliable way to determine whether an object is iterable is to call iter(obj).
I have to take a practice test, so I have to tune out interesting stuff.
This SO answer seems to suggest that iter(object) is not the best way anymore: https://stackoverflow.com/a/61139278
isinstance(MyIterable([]), Iterable) in your example yields False btw
despite being actually iterable
Yeah
a function that doesn't block the current thread of execution
I think these two questions, about learning asynchronous functions and tkinter, would fit a help channel better
sure
how do i do a help channel
Oh.... didn't saw the channel name...my bad ..sorry
This is a discussion channel to discuss Python itself, from a higher-level and more abstract perspective. We do have up to 32 help channels. (See #❓|how-to-get-help for info on how to open a help channel.)
@wide shuttle yo how do i see if someone answered my question
@unkempt rock going to the channel where you asked the question. You can use the Discord client to search for messages from yourself and then go to the one where you asked your question.
yes
channels = *channels```
How do I unpack a list in a variable? The above is wrong but shows what im trying to accomplish
if you just want the first element, channels, = channels
what should be the result then?
[[['a', 'b', 'c', 'd', 'e']], [['f', 'b', 'c', 'd', 'e']], [['f', 'b', 'c', 'd', 'e']], [['f', 'b', 'c', 'd', 'e']], [['f', 'b', 'c', 'd', 'e', 'f']]]
to
[['a', 'b', 'c', 'd', 'e']] [['f', 'b', 'c', 'd', 'e']] [['f', 'b', 'c', 'd', 'e']] [['f', 'b', 'c', 'd', 'e']] [['f', 'b', 'c', 'd', 'e', 'f']]
channels = [*channels]
``` will unpack the list into another list
that is not a data structure
thats the before and after
a single variable always holds a single value
Can I make my own web scraper in python as I can in Perl? and where can I find the documentation?
you can, probably using beatifulsoup4 or selenium
@flat gazelle what does that have to do with my problem?
Thanks @flat gazelle have used Beautifulsoup4 before, with IMDBPy
you apparently want multiple values in a single variable. Or do you want something such that when you do print(a) it does print(*original_a)
Look
I have [[['a', 'b', 'c', 'd', 'e']], [['f', 'b', 'c', 'd', 'e']], [['f', 'b', 'c', 'd', 'e']], [['f', 'b', 'c', 'd', 'e']], [['f', 'b', 'c', 'd', 'e', 'f']]]
There are 5 lists in a list, in a list
My friend says that you should always explicitly inherit from object
because explicit is better than implicit
but I don't think that applies to things you should know about the language.
I think it was a good idea in 2-to-3 transition times, but that should hopefully be over in 2020
also I see inheritance from object as an implementation detail and not much else
It's not an implementation detail, but nowadays I would see class Foo(object): pass similar to foo = int(3) . Superfluous, obvious.
I just see it as overly verbose syntax, anyone familiar with the language knows that everything's an object at the base so inheriting from it just feels overly verbose. No point in doing it for python3 only projects, and python 2 projects are hopefully migrated or migrating to 3
Maybe it's just that some resources/schools are still teaching python2, and that gets stuck
nothing like schools teaching depreciated versions 🙃
I know this isn’t the right server
But does anyone know what I’m doing wrong here
I’m Lowkey fuming that it’s not working
Shouldn’t be that hard
@unkempt rock This is not a help channel. See #❓|how-to-get-help or #discord-bots
@unkempt rock you just want mylist[0]
Yo there's this blog that has this awesome picture of the order of how __init__, __new__ and __call__ are executed during class creation and I can't remember it but I'm curious if anyone here remembers
… and Python objects in general — None of the existing articles [1] give a comprehensive explanation of how metaclasses work in Python so I'm making my own. Metaclasses are a...
call of the class shouldn't be called as a part of the constructor; the main things that happen is that new creates an object and then init of that object is called if it's an instance or a subclass of the cls passed to new
I think it was a good idea in 2-to-3 transition times, but that should hopefully be over in 2020
laughs in corporate
How could I define a dataclass from a dictionary like this:
dct = {"param1": [int, 0], "param2": [str], "param3": [str, "default value"]}
which should represent this dataclass:
from dataclasses import dataclass
@dataclass
class Entry:
param1: int = 0
param2: str
param3: str = "default value"
Probably easiest to use exec, unfortunately
oh
Actually scratch that
I didn't know about https://docs.python.org/3/library/dataclasses.html#dataclasses.make_dataclass
That may help
oh, that's handy, thanks
That should be able to do the trick pretty easily. How did I never know about that! 😅
why do you need to
woops
why do you need to specify the type if there's a value
casting?
Hello everyone, I'm tryna send an email using python's SMTP lib and stuff. Mail is working fine and sending. The mail message is in HTML format. Is there any way I could format the message, like so I personalize the mail. For instance, each mail addresses the user's name, like hello {username}. I was able to do this using plain text message, but I'm tryna implement it in HTML. Thanks guys, I could snap the code if you want.
Hi @tropic gale, you would just add a <p> element with your greeting text and template field like you show, and replace with the user name however you are doing it for plain text.
HTML is just plain text anyway.
@tropic gale This is not a help channel. See #❓|how-to-get-help
Can someone explain to me why 'foobar' in Class.__dict__ happens twice
Can't find it in the class and can't find it in the instance therefore it looks in the class again?
where did this drawing come from?
… and Python objects in general — None of the existing articles [1] give a comprehensive explanation of how metaclasses work in Python so I'm making my own. Metaclasses are a...
are you sure it's right? At the top is just Class, no instance, so where does instance come from?
ionelmc usually knows what he's doing, but it doesn't look right to me
the text clarifies it some: the first box is tp_getattro, not a native attribute lookup
it's news to me that that happens, but there's a lot of subtlety here
how do you think IDE creators decide what should be what color?
It looks like self (or whatever you call the first parameter of a non-static method) has its own color in PyCharm
built-ins also have their own color. Keywords share a color with objects that get a non-reassign-able name.
It looks like
self(or whatever you call the first parameter of a non-static method) has its own color in PyCharm
@boreal umbra it does?
mine is the same hm
a nice healthy orange
self is orange for you?
all parameters are orange
what version of pycharm?
for me the other parameters are white (default color)
also I'm using the dark theme for pycharm
i think in pycharm there's a setting for self and cls
Hey does anyone know how to code a custom stream bongo cat?
@dusky crescent I'm not sure what that is but you'll want to see #❓|how-to-get-help to learn about the help system. This is a discussion channel.
@unkempt rock as I said, this is a discussion channel
however
if you have an if statement, you'll have at least one line of code indented under that if statement. but there will probably be a few lines
these line(s) are your if block
after that block, you have the option of having a line that says else:, and after that you can have another block of lines that are indented under the else: line
that's your else block, and it's optional, but the else block will be entered only if the if block is not entered.
if you have any questions about that, please open a help channel and I'll explain it in more detail.
am I able to interact with another program (python script with interactive shell) with subprocess but keeping the state and continue sending commands to the 2nd program while parsing on the first? subprocess can keep the state of my 2nd program or I should use something else?
hi posted related on devops channel but wanted to ask along here, i'm trying to setup python auto linting check upon any pull requests to github repo, is this something doable only from github side? or should this involve build server like jenkins?
Sentinels is the only use case I can think of off the topic of my head
hey guys is pygames on 3.8.5?
hey guys is pygames on 3.8.5?
@exotic pendant try #game-development, this is for language discussion
oh my bad
is pyaudio available on 3.8
@scarlet ingot this is a discussion channel...
general?
k

