#internals-and-peps
1 messages · Page 73 of 1
That being said, the most recent JetBrains survey about what people are doing with python indicated that data science is the most popular use case in professional or academic settings, or something like that.
hey what do u mean by attributes in a class
is it a function defined inside of a class ?
@trail stratus class attributes are a thing, but you might be thinking of attributes that instances of a class have
An attribute is basically something you can get with the dot operator
Well, objects are basically ways of grouping related data and functions together
So attributes are all of those things
well what i mean is suppose there is a question
Make a class called Die with the attribute called sides
SO what is attribute here
If you made an instance of the Die class called die, it could have a sidesattribute. And you would get to it from die.sides
ohh i see thx
You could also make a Die instance called pie because why not
And pie.sides would give you data of the same type as die.sides
But it would be specific to pie instead of die.
Generally we wouldn't answer questions in this channel but I went with it because you were asking about how the language is designed
And the design of the language is part of the topic. Thanks for asking.
i see ok thx
Can some tell me how to connect wit.ai in nodejs with sink python script using socket connections and using bash scaript
@cyan bobcat take a look at #❓|how-to-get-help, though if you don't get a response you may want to try again during daytime hours for the US and Europe.
And Canada, I guess.
Ok I will try
@cyan bobcat your question isnt really for this channel, but wit.ai has a python library
How do y'all feel about imports of the typing module? I've started to consistently favour absolute imports of modules for some time now, but at least with the typing module, annotations become unwieldy quickly that way. Right now I do something like
from typing import Generator, List, Tuple
which works fine until you hit the line limit and Black bloats it across multiple lines. Is
from typing import *
really the way to go here? Curious to hear your opinions!
whats wrong with multiple line imports?
That's exactly what I want to avoid
🤷♂️ Typically any wild card imports are a bad idea
because it can easily lead to random overrides and poluting your name space
if you dont want todo it like the above do import typing as t so you can just do t.Dict for example
event though the () system really isnt that bad
Okay so here's a hot take:
If you do
from __future__ import annotations
It should also import all types from typing and also become standard behaviour in Python 4.0
that would generally just be needless name space poluting tbh
3.9 brings general types like list etc... being inbuilt
so instead of doing typing.List[str] it will become list[str]
That's nice, I didn't know that
I think I will go with multiple import statements from typing instead
Usually looks fine in parentheses with implicit line continuation, but yeah 3.9 should get the number of them down significantly or moved to other modules
I like 't-dot notation' with import typing as t and then t.List, but others hate it
I prefer to import them directly but have to admit that the import and the diff you get out of it are not that nice for more than a few names
3.9 will be so nice for that
You should take a look at #❓|how-to-get-help
Also, “best” isn’t a thing in programming
It is a form of engineering, there will always be tradeoffs
@unkempt rock also #cybersecurity
dont know where is proper channel for this
so I'm writing library for python but I need inspiration, how can I find?
I started but can't find other things for this library
What are you writing a library for?
how does pypy compare to c?
so I have some math methods, validation
@heady siren PyPy is a Python implementation, and C is a separate language... So can't really compare them
yeah
If you're doing just number-crunching tasks, it can be at least a few times slower in PyPy than in C
hmm general purpose, maybe shrink the range?
seems pretty niche given that numpy exists
Well, generally, the only way to find out is to implement and measure 🙂
@plush root a library that does math things and some kind of validation is probably way to broad and unfocused, yes
ok so maybe math lib like extended one
numpy is not a free speed up for any kind of program
Well, doing computations in numpy instead of pure python is a free speed up
it's not even that uncommon to see people write numpy code that ends up worse than pure python
"well if i use list.append here, i can use np.append right ? what's the problem" @undone hare
then you end up with a numpy rewrite that is orders of magnitude slower than the pure python counterpart
Sure, but I’m assuming that the code is correctly written 
Turns out that the fastest way to add two 2-element tuples elementwise is to write raw bytecode with stack manipulations.
And numpy was the slowest method
so yes
... lol
The general advice about the volume of Data is also relevant
If you just have very few items, the overhead of creating the numpy array itself could take away any potential speed gains you would have gotten.
how can i do the part that said get position of specefic number in lists?
Wrong room. Try #❓|how-to-get-help
PEP 584 has this peculiar line: "each of which must be a dict (or an instance of a dict subclass)". Why did the author explicitly mention the part in parenthesis?
there is a difference between exactly a dict and a dict subclass, though I cannot think of anything that cannot take a dict subclass and takes exactly dict
@hearty monolith "be a dict" is ambiguous (because English)
!otn a don't-be-a-dict
@spark magnet How come "be a dict" is ambiguous? English isn't my first language
(replace the last letter with a k)
does it mean type(d) is dict or isinstance(d, dict) ?
isinstance() seeing the part in the parenthesis
Wait, those aren't the same?
They aren't, type() will not work on a subclass of dict
Ohhh
@undone hare that's what the doc means, i was answering why "be a dict" is ambiguous.
Oooh, right, I misunderstood
The fact that it is between parenthesis is probably because it was added by the person who helped write the PEP, as it was originally ambiguous
So, if I understand everything correctly, type(d) is dict asks explicitly if whether d is just a regular dict, while isinstance asks if the dict class was involved with d in any way?
isinstance can return true for subclass instances or classes that implement an instance hook, while type(d) is dict takes the value returned by type and checks if it's exactly the dict class (thus the is operator)
Yes.
you can edit it, and it will change the output
I know, I made this feature haha
Dunno where the error is though haha
missing opening quote on last line
missing a quote on line 4?
Thank you!
!e
class MyDict(dict): pass
my_dict = MyDict()
print('type :', type(my_dict) is dict)
print('isinstance :', isinstance(my_dict, dict))
@undone hare :white_check_mark: Your eval job has completed with return code 0.
001 | type : False
002 | isinstance : True
It is hard to spot errors on the new mobile codeblock tbh
type(x) is faster, depending on your use-case, you might want to use it
why on earth would speed matter?
P1. To understand something, you need to access its root
P2. X wants to become an evil genius
P3. To become an evil genius, X must understand evil
P4. Premature optimization is the root of all evil
C1. P2, P3 => X must understand evil
C2. P1, P4 => To understand evil, you need to optimize prematurely
C3. C1, C2 => X must optimize prematurely
proof
won't accept this until you can show premises are consistent
please rewrite in ZF + C
!otn a don't-be-a-dict
:ok_hand: Added don’t-be-a-dict to the names list.
return list(filter(lambda rule: rule[0] == nonTerms, grammar))```
can someone explain this return line to me?
which OpenCV version is compatible with Python 3.7.6?
why on earth would speed matter?
@spark magnet I was working on a [de]serialization framework and compared to type, isinstance is hella slow. I used standard primitive types, so it was exactly what I needed
well in the end I wrote some rust which gave me huge speedup but don’t mind that 
I guess it's predictable
Type does what, returns obj.__class__? While isinstance has to check if there are hooks present and adjust accordingly, check the mro...
obj.__class__ and type(obj) are the same, except when someone defines __class__ in obj kek
and yeah something like obj.__class__ in cls.__mro__ should be not bad
the point is, both an is check and a type call are really cheap and straightforward while isinstance has a lot going on under the hood, so it's not a surprise that the latter is significantly less efficient
Aww they got rid of reactions again
lets say we have this scenario
class A(object):
def method1():
pass
def method2():
pass
class B(A):
pass
I want to write a descriptor that effectively blocks method2 on B. Like I don't want that method to exist for B because it would do something undesirable. Can I delete it? Write a descriptor? I'd have to do this a few places and would rather not have to redefine the undesired methods just to raise a NotImplementedError.
Nvm I could literally do this
class NotDefined:
def __get__(self, obj, type=None):
raise NotImplemented
class A(object):
def method1():
pass
def method2():
pass
class B(A):
method2 = NotDefined()
isnt there some kind of name thing for descriptors?
to know what its attached to?
!otn a don't-be-a-dict
@peak pollen does this mean we can havepython-object-oriented-programming?
__set_name__
is the python virtual machine considered a LLVM? what's the difference between python VM and LLVM?
@forest flicker what is a python virtual machine?
@forest flicker As far as I know, LLVM is a name of a specific toolset https://en.wikipedia.org/wiki/LLVM, not a general concept
LLVM also pretty much has nothing to do (anymore) with VMs, despite its name
@edgy vault I would open a help channel for that quesiton; see #❓|how-to-get-help
ow thanks
@forest flicker VM just means "virtual machine", ie a machine that has no actual silicon. LLVM is a VM because it's targeting a bunch of "virtual machines" in the different steps of the compiler. Very different from the python VM which is a runtime thing.
And VM as in VirtualBox/VMWare/etc is a totally different thing too, so it's confusing that there are many things that use the same name.
hey guys 🙂 i’m gonna be bored the next few days and wanna try something new. can anyone recommend some things I should try and make in either a GUI or CLI. this is the advanced discussion so i mean can it be something that might take more than the weekend aha. thank you 🙂 (also ping me if you reply)
Have you tried getting python macros to work within Gnumeric?
Hello, I'm new to python but eventually I want to learn AI, I want to know what IDE to use which would be the best for it. A few people told me before but I want to know from others too.
hey anyone?
can anyone help with OpenCV?
i am trying to make hand gesture recoginition
LLVM is a VM because it's targeting a bunch of "virtual machines" in the different steps of the compiler
LLVM is not a VM
The name is a relic of the past, there is some IR that's common for all architectures, then using llc you convert that IR to whatever your machine wants
LLVM IR is much closer to a low-level C than something like JVM bytecode
LLVM is essentially a compiled to machine code programming language designed to be easy to write for compilers, rather than humans
Two problems with that:
- Saying "LLVM is not a VM" is nonsense without defining "VM".
- Any IR can be seen as the byte code of a virtual machine that can interpret that byte code.
@flat gazelle that doesn't sound right at all. LLVM is absolutely not a programming language by any stretch. It's a toolbox to build compilers.
Brothers, how can i in my voice assistant add control of openhabian??
how can python reverse a generator?
does it exhaust it once and then return them one by one from a new generator?
reversed(range(10)) works and returns a iterator
reversed doesn't accept a generator, it accepts a sequence 🙂
range(10) is not a generator -- it's a special range object. It's an iterable sequence, and you can do cool stuff with it.
!e
r = range(3, 10)
print(r)
print(r[0], r[1], r[3:6])
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
001 | range(3, 10)
002 | 3 4 range(6, 9)
So reversed does something like:
def reversed(sequence):
for i in range(len(sequence) - 1, -1, -1):
yield sequence[i]
There's also a __reversed__ dunder that you can implement if there's a more efficient way of reverse iteration
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
<method '__reversed__' of 'range' objects>
yeah
@molten spruce This is not a help channel. Check out #❓|how-to-get-help .
Okay
try:
sensor_data: pd.DataFrame = {
'all': lambda: pd.DataFrame([...]),
'outside': lambda: pd.DataFrame([...]),
'useful': lambda: pd.DataFrame([...]),
'family': lambda: pd.DataFrame([...]),
'no_child': lambda: pd.DataFrame([...]),
'column': lambda: spd.DataFrame([...])
}[sensor_filter]()
except KeyError as err:
raise KeyError(
f'Invalid sensor filter supplied: {sensor_filter}') from err
Is there a better way to do this? The context is that the user provides one of these strings, if it matches the dict returns the lambda that generates the data. I dont want to allocate memory for all of the branches, so this way it only creates the dataframe code if there is a match
hey um
is there a type annotation for a numeric string
like there's string
and number
but what about both
I mean conceptually that probably wouldn't be a type anymore
why not
Well, that would be some kind of a dependent type, I suppose 🤷
Well, you could have Literal['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', ...] 😄
Or maybe you could have Sequence[Literal['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']]
Yeah, that's probably the closest thing ^
Fuck yes let’s introduce dependent types to python 🙂
That’s more just c++ templates than full blown dependent types tho (I think?)
import typing as t
N = t.TypeVar("N")
class Zero:
pass
class Succ(t.Generic[N]):
pass
Nat = t.Union[Zero, Succ["Nat"]]
😎
Flashbacks to the first thing I learned when a friend was explaining something (in I think Agda?) to me
Wonder if someone’s implemented something like this in python
did u remove bounds?
yeah, it didn't work for the example for some reason if you leave the bound
class Vector(t.Generic[N]):
pass
def cons(x: t.Any, vec: Vector[N]) -> Vector[Succ[N]]:
...
def f(v: Vector[Zero]):
return cons(42, v)
def g(v: Vector[Succ[Zero]]):
return cons(42, v)
def h(v: Vector[N]):
return cons(1,cons(22, v))
Pyright infers f's type to be Vector[Zero] -> Vector[Succ[Zero]], g's type to be Vector[Succ[Zero]] -> Vector[Succ[Succ[Zero]]], and h's type to be Vector[N] -> Vector[Succ[Succ[N]]].
anyone know how simplify this boolean? (p∨¬p)∧(q∨¬q)
@trim glade True 🙂
for further questions, this is a discussion channel (see descrption), not help channel; boolean algebra probably belongs to offtopic
so that is a Tautology then right?
your right! Thanks a ton
I gotta do it
>>> @ExtremeEdgeCase
... class TechnicallyNotAlways(metaclass=Nitpick):
... def __init__(self):
... self.state = False
... def __bool__(self):
... val = self.state
... self.state = not self.state
... return val
...
>>> a = TechnicallyNotAlways()
>>> a or (not a)
False```
You should inherit from the Nitpick class
fixed it
Technically, you didn't inherit from Nitpick, you used it as a metaclass
so you didn't fix it
technically
I feel like a metaclass is more appropriate here, because type(TechnicallyNotAlways) is Nitpick
@spice pecan Technically, not necessarily -- ExtremeEdgeCase can replace it with something else
Very true
I win the nitpick battle then 😎
I seem to recall someone mentioning that there was an issue with using return self at the end of a class in order to enable method chaining, I'm not sure what the issue actually was though. What's wrong with that?
Well, in Python mutating methods return None, it's just a convention
curiously, in Smalltalk methods return the instance by default instead of nil
there's no reason not to then unless it's something a bunch of others are likely to want to use?
Well, yes
or even in that case i guess it's alright if it's consistent
Guido didn't like fluent interfaces afaik
can some one help me with this proplem
@empty kite ah, "fluent interfaces", is that what they're called then
I'm guessing he's not a big fan of sklearn's design in that case 😄
Two problems with that:
- Saying "LLVM is not a VM" is nonsense without defining "VM".
- Any IR can be seen as the byte code of a virtual machine that can interpret that byte code.
@half wolf If we use the regular VM sense of "emulating a computer", then LLVM doesn't come with one, in fact, they are adamant that LLVM should not be called a virtual machine
The LLVM Project is a collection of modular and reusable compiler and toolchain technologies. Despite its name, LLVM has little to do with traditional virtual machines. The name "LLVM" itself is not an acronym; it is the full name of the project.
https://llvm.org/
And it's safe to assume lakmatiol was referring to the IR in his message
but what about both
@solemn jewel what do you mean?
like a value that is either an int or a str?
or like a str which can have only numeric characters in it?
or something else?
or like a str which can have only numeric characters in it?
this @gleaming rover
this @gleaming rover
@solemn jewel there isn't
but you could make it
that'd be a new type
oh ok then
is there a reason why async lambdas were never implemented?
i saw https://bugs.python.org/issue33447 this issue of someone asking about it, and they seem like they'd be really handy (@ me)
@teal yacht yea I know all that. Doesn't change anything imo.
@unkempt rock The thing about lambdas is that they're atomic in nature
They evaluate just a single expression, unlike coroutines which can be fairly elaborate
Well you wouldn't really want to evaluate more than one expression in a lambda, that would border around being un-Pythonic
async lambda: await coro can be lambda: coro and is used about the same.
@brave badger doesn't mean atomic in the normal way here I believe. You can still get a context/thread switch in the middle of a lambda.
Hmmm.. Or maybe pure is confused.
Well you wouldn't really want to evaluate more than one expression in a lambda, that would border around being un-Pythonic
@brave badger
What does that even mean? Lambdas don't syntactically support anything else than one statement. It's not just unpythonic, it's impossible in python to do more than one.
But one statement can also encompass the entire universe of possible computation.
I may be confusing terms, yes haha
Lambdas don't syntactically support anything else than one statement. It's not just unpythonic, it's impossible in python to do more than one.
I was referring to using various hacks to do more than one thing at once in alambda
But one statement can also encompass the entire universe of possible computation.
That's true as well, I guess what I really meant was that havingasynclambdas wouldn't really add any major benefits given that there's no real way to "compose" coroutines aside from the usualasync/awaitsyntax.
Also I meant atomic is in does one thing and one thing only
I just consider lambdas to be anonymous functions with an implicit return that are a bit crippled.
Which is what they are :)
Fair enough
I think lamda function is like a fast food things. It's a simple way to create some function
It's useful when you need to wrap some operation without create any function block
useful when working with DataFrame : Lambda function
Just curious, how often do coroutines get passed as callbacks?
Just curious, how often do coroutines get passed as callbacks?
@brave badger it depends on the use case, I think
@brave badger if its a mostly async system, alot. Any of my webserver and framework stuff supports both coroutine and sync function callbacks because of the nature of this sort of stuff
oh there is advanced room here
I was just looking at itertools.groupby and am not sure where to see what's really going on with it. It seems that it's defined here https://github.com/python/cpython/blob/master/Modules/itertoolsmodule.c#L66 in cpython,
In the output of itertools.groupby?? I have:
Init signature: itertools.groupby(iterable, key=None)
Docstring:
make an iterator that returns consecutive keys and groups from the iterable
I'm not sure how to trace what is going on though, for example in the following:
arr = [(1, "A"), (1, "B"), (1, "C"), (2, "D"), ("k", "E"), (3, "F", "Z")]
for k, g in itertools.groupby(arr, lambda x: x[0]):
print(list(g))
# outputs:
# [(1, 'A'), (1, 'B'), (1, 'C')]
# [(2, 'D')]
# [('k', 'E')]
# [(3, 'F', 'Z')]
How to know what's going on within the itertools function? Here https://github.com/python/cpython/blob/master/Modules/itertoolsmodule.c#L80 it seems that this is the function that's called? Maybe it's obvious if you know C?
well, it just initializes an itertools.groupby object
@magic python couple tips in these kinds of cases: 1. as someone also more comfortable with python over C, i sometimes find tracing functionality in pypy easier for understanding things. and 2. always check documentation first. in this case, they actually provide an almost equivalent python implementation of groupby. check here
... okay clearly thats not how hyperlinks are created on discord. 😛
@visual shadow cheers, i've never looked at pypy, just heard of it - what would be done in this example wrt pypy?
basically, the implementation of pypy is essentially guaranteed to be python code. so, same thing. their github source code, and you find your relevant function. just, you'll be guaranteed that its written in python, so it will be easier to read.
cpython will implement a lot of core functionality in C code. so it gets harder to trace things down correctly.
what often happens is that you end up looking in the wrong place without realising it
hm, interesting. I will never call pypy code though presumably, it'll be the cython be default?
or is pypy sometimes used without me knowing
oh. uh. just to clarify terms, cython is something else entirely.
and the "implementation" is decided at the time of installing. if you dont know your implementation, it's definitely cpython
so, you wont have pypy unless you explicitly install pypy
i'm just reading through pypy site, don't really understand why there's a need for both pypy and cpython
seems like a lot of duplicated work?
absolutely. it's entirely duplicated...and yet that's where magic can happen
it's like you can get from point A to point B in a car. so why have many different types. 😛
they end up having their pros and cons. certain implementations make certain things easier. sometimes you just want certain behaviours that one implementation doesnt give. for example, cpython is particularly good at interfacing with C code. pypy however is JIT compiled, so it can be sometimes quite fast for native python code, more so than cpython
I mean - was there originally a question as to which approach was best and Cpython "won" or something? I get different ways for different things, I'm not sure if there would be (in the ideal world of a cpython / pypy dev) just one of these though
well, mind bendingly enough, pypy is written in python. so, it couldnt really exist till python was invented
so in this case, it's more like "lets build something first" and C was the defacto language for doing things at the time i suppose. and pypy as an implementation couldnt exist till python was created
C offered a lot of inspiration for guido when he was working on python, and you can sort of see it too.
as for the other benefits, i imagine it was the usual, C is fast, etc etc kind of deal
so if there was a big meeting and everyone was going to use one or the other from this point, assuming either option was equally easy to implement, pypy would be the more sensible choice?
sadly, the answer is: it depends. 😄
damn it
if pypy was just blanket better, then probably yes. i dont think that's the case
specifically libraries related to C and cython struggle on pypy last i heard. say, numpy and so on
pandas 😦
i will admit im not too sure about the current state of pypy, but i think it was falling behind last i saw.
so, if such a meeting were to happen right now, cpython would win just by virtue of "its already ahead. dont fix what aint broken" etc. and yet...theres a clear appetite for JIT compilation, it's why pypy is probably the only other implementation of python that people still talk about
the start up time of pypy is awful --- and most python scripts are probably small enough
I don't think it would be a good de-facto
I'd be more interested in rust-python
why'd rust be better than C
it's not better, it's just another implementation
for the fun of it? Or are they making a case that it's an improvement on Cpython
Pypy is behind because cpython is always moving. But the C extensions stuff is mostly fixed afaik. But there are also better ways to make C extensions that make everything better for everyone.
does anyone know if I can output the audio of pyaudio to the microphone?
i can't found it in stack overflow
Hi... I'm programming a NeunoralNetwork and I am already done with the code and the plot... I just don't know how to get predictions for my examples now.
If you are rly fine with them, please help me... I get desperate ☹️
this isn't a help channel
@deft pagoda Rust python has the potential to be really powerful if they're able todo what they want todo by doing the entire interpreter in pure rust rather than using bits of the C code
actually they might have done that already but low api coverage
either way it would be amazing to see them do it and actually has the chance to make python more viable in redistribution using WASM etc..
this is a scary channel 🤣
@plush sentinel send sound TO the microphone? Sure. Plug in the microphone in the speaker jack. It's a very bad speaker though.
@radiant fulcrum seems improbable you can get significant gains. Some parts maybe and the security would be much easier to guarantee/validate but that's about it.
@half wolf I think the most interesting bit is the experimental Jit implementation
Which has the potential to provide a much better system compared to PyPy making use of compiler abuse, but this is still a long way off
"compiler abuse"? It's literally a JIT. Some of the problems of pypy not delivering the hoped performance improvements are due to things rust can't fix, but cpython extension emulation and JITs not being enough for example. Rust can't fix those things, it can only fix stuff like the warmup time (which is admittedly a big problem!) and security (which isn't a problem with pypy but with cpython).
I'm getting an error executing python OOP program that i'm currently working on for college. Hoping if anyone can help me out.
@charred minnow This is not a help channel, see #❓|how-to-get-help. You can claim your own help channel and ask here -- and don't ask to ask, just ask your question and attach the code that you have.
I always dream about python getting to speeds comparable with javascript
as much a js has some really weird and awful characteristics, you cant complain at the Node runtime
Is it pretty speedy?
compared to python yeah
Node is a JIT which is partly responsible for it's speed but overall its alot faster than python usually especially for web frameworks and stuff like that
I'm always confused why CPython hasn't implemented JIT
i imagine because of the old issue of the interpreter having such a fucking weird set of quirks
Maybe in Python4
js doesnt have anywhere near as much control over the runtime as python though
which would cause a issue for alot of systems if python did a similar thing that would both fix stuff but also break alot of stuff
also python has more complexity than js
like dunders
plus js needs to be fast
because web
it doesnt really
most people's js wont be anywhere near the same speed as what it could be
js is designed to be sandboxed tho which python is not
js development gets more funding because web needs to be fast
which is why you dont have that high level of runtime exposure as python
runtime exposure?
you can do all sorts with python's runtime
ah
things that you cant even dream of doing in js which alot of systems like sentry to name one use
you mean like ctypes?
no i mean like litterally controlling how the garbage collector works, getting the interpreter frames editing raw memory etc...
How about FastAPI framework? It said that it's the fastest Python web framework, on par to NodeJS and Go
its no where near the speeds
FastAPI is one of the fastests python frameworks because it runs on uvicorn which is the current fastest python webserver
even then Uvicorn is a good 3-4x slower than the fastest NodeJS webserver and go's fastest is a decent 5x faster
Oh so the fastest python framework still no where near the speeds?
not really
Ive made a experimental server that uses Go to bind with python frameworks
but that still isnt as fast as Node's fastests stuff
at best it gives about a 30% performance increase or so
so speed is generally the thing you dont go for with python web backends you go fro the development speed not the execution speed
I see
which tbf hardwear is often much cheaper than man hours for a company
slower framework -> throw more server at it
slower development speed -> cant really do much
why altho Rust has some of the fastest servers for the web its not the most common
because its very slow to develop compared to python
Maybe that's the reason why my company at work still using Python for their server even when their client is banks and stock exchange which is really need speed
btw if you want to have an idea https://www.techempower.com/benchmarks/ is a 3rd party benchmarker which is generally the 'standard' for comparrisons
slower framework -> throw more server at it
slower development speed -> cant really do much
@radiant fulcrum wow, really make sense now haha
Yes, i got the information about the comparison from that website too> btw if you want to have an idea https://www.techempower.com/benchmarks/ is a 3rd party benchmarker which is generally the 'standard' for comparrisons
@radiant fulcrum
slower framework -> throw more server at it
well... that will improve throughput but might not improve latency.
For example, if your website calculates (((2 ** 2) ** 2) ** 2) ... ), you can't improve your speed by buying 1000 servers and running a version of Basic implemented in Python on it
For example, if your website calculates
(((2 ** 2) ** 2) ** 2) ... ), you can't improve your speed by buying 1000 servers and running a version of Basic implemented in Python on it
@grave jolt that sounds quite beautiful
BASIC in Python 🤔
but anyway, yeah, I think, relatively speaking, most backend tasks are short-running?
beazley did something similar -- emulated a superboard in python
David Beazley's PyCon'2011 Talk from Atlanta Georgia. A mirror of original content posted at http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-using-python-3-to-build-a-cloud-computing-service-for-my-superboard-ii-4896844
David Beazley teaches intense in-person Python...
@grave jolt yeah latency is another issue
python's latency is generally higher than others like compiled frameworks but thats to be expected
But why Python is mostly used on data science which have a lot of heavy-CPU task if it slow?
you can call compiled C code in modules like numpy
also, data scientists aren't developers --- having a language that's easy to use and slow is better than a language that is fast but difficult to write
Oh ok I understand now
But why Python is mostly used on data science which have a lot of heavy-CPU task if it slow?
@oak saffron most of the CPU-heavy stuff is done in C
which, tangentially, is why numpy arrays generally shouldn't contain Python objects
In [1]: import numpy as np
In [2]: a = np.arange(1000, dtype=int)
In [3]: b = np.arange(1000, dtype=object)
In [4]: %timeit a.sum()
2.21 µs ± 11.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [5]: %timeit b.sum()
22.1 µs ± 376 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
operations in C vs in Python
Django allows you to define custom commands by putting modules in a set location and uses the following code to detect them:
def find_commands(management_dir):
"""
Given a path to a management directory, return a list of all the command
names that are available.
"""
command_dir = os.path.join(management_dir, 'commands')
return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])
if not is_pkg and not name.startswith('_')]
Are there any potential issues with the this method, particularly the use of pkgutil?
@safe hedge what kind of issues are you thinking of
I don't really know tbh. I always worry about the robustness of code that is introspecting source code itself
That's not inspecting source code, afaics... It's searching for modules on disk
That's not introspection, that's plugins
But your app code could be installed no?
that's pretty close to what I mentioned earlier about how git finds subcommands, in fact
That's not introspection, that's plugins
@raven ridge Yeah this was a pure python example I thought of after our discussion of the git plugin system we mentioned before
Haha beat me to it
😄
Just wanted to see if anyone had any clear cons with this code tbh
One issue I considered is that surely it has to recalculate the available commands every time you call the script. Which seems like unnecessary overhead.
But your app code could be installed no?
@safe hedge I don't follow this - what does whether it's installed or not have to do with anything?
One issue I considered is that surely it has to recalculate the available commands every time you call the script. Which seems like unnecessary overhead.
@safe hedge it's a one-time startup cost
which is necessary, because every time you run the available commands could change
I was about to say the same - doesn't seem unnecessary to me.
unless you mean "every time you run the function"
But if you have the script available as my_command then doing my_command help then my_command task1 help then my_command task1 --opts you've calculated it 3 times
But if you have the script available as
my_commandthen doingmy_command helpthenmy_command task1 helpthenmy_command task1 --optsyou've calculated it 3 times
@safe hedge it's a fast operation
relatively speaking, so it doesn't really matter.
but anyway the available commands could change between invocations.
For the cost of doing 1 run. Thought there might be a good way to cache/update the available commands every so often
For the cost of doing 1 run. Thought there might be a good way to cache/update the available commands every so often
@safe hedge why?
Running on a Linux system, by any chance?
it's too low cost to matter IMO
Like maybe have a refresh command that would reread the plugin folder and add new commands
excessive cognitive overload IMO
Kind of like how supervisor reload/update are used to pickup new tasks
Running on a Linux system, by any chance?
@raven ridge Mac and Linux yeag
Like maybe have a
refreshcommand that would reread the plugin folder and add new commands
@safe hedge There's things that work that way, too.vimuses something like that for its:helpdocs - you need to use:helptagsto refresh them.
like you could do it, but as they say...
ever used strace?
there are only two hard problems: naming things and cache invalidation
and off by one errors.
Fair. This is the sort of advice I'm looking for tbh. I don't know what the overheads for this sort of thing are
minimal
premature optimisation is the root of all evil
unless you have 500 installed apps with 50 commands each
then okay, I could see that happening.
And tbh most of the time I expect these commands to be set to run on a cron more than used interactively
The first rule of optimization: don't. The second rule of optimization: don't, yet.
but you probably have like 20 commands in your project, max?
So the overhead probably is not significantly problematic
I mean
Django doesn't even cache its own commands
and there are parts of Django which have been optimised to degrees I would say are a little...ridiculous
but you probably have like 20 commands in your project, max?
@gleaming rover Err probably like 6/7 top level ones, then subcommands
okay, maybe not "ridiculous", more "impressive"
strace is a command that shows all of the system calls that your program makes as it's running.
def now():
if settings.USE_TZ:
# timeit shows that datetime.now(tz=utc) is 24% slower
return datetime.utcnow().replace(tzinfo=utc)
else:
return datetime.now()
^ Django
I think if you were to ever run your interpreter under strace and look at what it shows you, you'd understand just how trivial the handful of extra disk accesses used for finding plugins are.
django.utils.timezone
and also, one-time expense (within reason) is a lot more tolerable than something slow that runs in a tight loop
So in other words. If I were to roughly follow the Django management command model that would be a reasonable solution?
yes
I have lots of rubbish running on startup and Django still takes less than a second to run for me
well, maybe not lots, but some
in particular I also have a couple of separate plugin systems that kinda work like that
~>strace -e stat python3 -c 'import sys' 2>&1 | wc -l
171
Just bringing up the interpreter and importing a single module requires hundreds of stat calls alone.
I'm thinking of doing it slightly differently by not having a whole Command base class setup, but rather just call the main() in any modules in the right path
your 6/7 extra files don't make a dent.
It's for work. But effectively I am the main user
if someone else will read your code
it's generally better to follow conventions that have been around for a long time and make reasonable sense, like this.
this seems like a pretty clear case of premature optimisation to me
this seems like a pretty clear case of premature optimisation to me
@gleaming rover Which bit?
I mean, we all love a good day spent prematurely optimising something that is already much faster than it needs to be, but 😉
The whole plugin idea or the idea of caching the commands
@gleaming rover Which bit?
@safe hedge the caching idea
Oh right yeah I'm more than happy to not do it
As I said that's the sort of advice I'm looking for
and most people who use Django will expect your commands to have the structure that commands mostly have in Django projects
that, more than anything, IMO, is a reason to do things that way
This is not for Django btw
for work in particular, there's absolutely no value in making something faster than it needs to be. You're spending the company's money to achieve something in excess of the business requirements imposed by the product owners.
oh, okay
Just using their model as a guide for that plugin system basically
then at least don't have a redundant subdirectory
like /management/commands 😡
(Django)
Because I want to be able to define new commands without needing to update multiple parts of the codebase
and also, yeah, I'm not sure about the subclassing model
okay so the topic now is more how to model a plugin system?
So right now my idea was to have the following structure:
pkg
- cli
- command1.py
- command2.py
- subpkg
- code_in_command1_and_2
- more_code_in_command1_and_2
- subpkg2
- code_in_all_commands
- code_in_some_commands
Where basically I can just write modules/subpkgs with the code that does stuff and then have a cli subpkg where I can just write commands which can use any of the code in the other subpkgs
So really my commands are separated from the base functionality code but still in the same overarching pkg so it's easier to install
okay, fair enough
then set something like cli.__main__.py to be an entrypoint that runs the whole find_commands part
Hello friends, I am having trouble understanding the @staticmethod what is the real use case for this? According to geeksforgeeks, it sounds like it is just a way of getting your ide/linter to stop yelling at you for using self in a method, haha. But I would like to actually understand this better.
Hello friends, I am having trouble understanding the
@staticmethodwhat is the real use case for this? According to geeksforgeeks, it sounds like it is just a way of getting your ide/linter to stop yelling at you for usingselfin a method, haha. But I would like to actually understand this better.
@zealous hawk static methods are methods that are conceptually still linked to a class, but don't require access to either instance attributes or class attributes.
It's a pretty common opinion that @staticmethod doesn't belong in the language and should never be used. Guido himself has said that he regrets adding it, and that it was only created because he didn't fully understand the problem he was trying to solve
Yeah, I understand this much. What is the specific reason to use this instead of a classmethod
i.e why should I do this
class MyClass:
@staticmethod
def add():
return 5 + 5
instead of (obv bad):
class MyClass:
def add(self):
return 5 + 5
It would be better to do:
def add():
return 5+5
It's a pretty common opinion that
@staticmethoddoesn't belong in the language and should never be used. Guido himself has said that he regrets adding it, and that it was only created because he didn't fully understand the problem he was trying to solve
@raven ridge I agree with the first part of your statement, but Guido isn't always right
I agree with that, too. Just an example of someone high profile who espouses that view.
I'm inclined to agree: @classmethod solves a genuine problem, but every use of @staticmethod could be replaced by a free function.
okay, actually sometimes I use staticmethod when I don't want to nest functions in a class
why not a free function?
the convenience it brings is that automated refactoring moves them, too
like moving the class to a new file?
yup
hm. 🤷
which is a super minor thing, and it doesn't happen often 🤷♂️
sometimes I feel like 4 space indentation is a bit much
because methods are already indented once, and then functions nested in methods again
but I've gotten used to it
I like using a staticmethod when I want something that could be a free function to be clearly linked to a class
if it could be a free function, I'd argue that it shouldn't be linked to a class.
something that doesn't depend upon the class or any of its state shouldn't be linked to that class.
I like using a
staticmethodwhen I want something that could be a free function to be clearly linked to a class
ty, this is what I thought it was for, but figured there must be more functional use
what about non-public helper methods?
I have also used it for some subclassing stuff. Like I have a DB wrapper and I use a staticmethod which is just pass in the base class to allow some modifications to connection objects in subclasses
and ty all, this is very helpful
say you have a class that is for drawing PDFs and takes in some complex object; you want to write a method that extracts certain attributes from that object
what about non-public helper methods?
if they don't useselforcls, then they should be global functions in the module that defines the class.
But that seems unnecessary if it's only ever going to be used by the class
if it'll only be used by the class, make it a private method in the module by prefixing it with _
it's more a namespacing function in that case, I think
Another DB example actually. I have a DB that uses 'T/F' for true/false (don't ask) so I have a static method on my client class for that DB which takes a dict and changes all the true/false to T/F
if it'll only be used by the class, make it a private method in the module by prefixing it with
_
@raven ridge if you have multiple classes in the module, but only one class uses that function, I think it should stay in the class
It could be a free function but tying it to the client class makes it super clear when and why it should be used
And since it's mostly used internally it seems easiest
I disagree. A static method is a free function that you have namespaced below a class. But if it doesn't depend on that class - it uses nothing from self or cls - then it shouldn't be namespaced below that class. It could be more generally applicable.
yes, that's the thing
when you use @staticmethod you are using classes-as-namespaces instead of classes-as-data-and-function-containers
so I can see the weirdness in that
yes, exactly. in a nutshell, @staticmethod is a way of using a class as a namespace, but it's not particularly Pythonic to use a class as a namespace. In Python, modules are the idiomatic way of namespacing.
the idea of "class as a namespace" is a Java-ish idea - it's something that exists in OOP languages that don't have the ability to create free functions.
C++?
If I have a module with two classes and a function that could be a free function but will only conceivably be used by one of the classes I think it just helps
I disagree, and my opinion appears to match the majority consensus of Python programmers. Googling for "python staticmethod" will find many more people who espouse my viewpoint.
yes, I think it's quite clear that most people are against staticmethod
I mean, I don't necessarily disagree that they "could" be free functions and I'm not saying you "should" use a staticmethod. But I just don't really see the harm
I have always thought it was odd and never really understood the purpose for it. It sounds like it is pretty much only a stylistic consideration.
I mean, I don't necessarily disagree that they "could" be free functions and I'm not saying you "should" use a staticmethod. But I just don't really see the harm
@safe hedge but this.
if you want to have multiple classes that have no state within a module, i think it's useful
it is pretty much only a stylistic consideration.
Yes. It's a free function that happens to have been namespaced under a class.
why have a class with no state?
why have a class with no state?
@spark magnet marker classes? don't think that's what they meant though
honestly, though, all my staticmethod uses could be nested functions
we're not talking about class with no state, we're talking about method that doesn't use that state.
that too
but, as discussed above...indentation + convenience of IDE move
and I don't actually know anyone who does what I do so 🤷♂️
incidentally, does anyone use 2 space indent?
because I do that in like every other language...
i hope not lol - it's not clear enough for me (2 spaces)
which is basically JS/Scala
I guess I can think of one case where it might make sense? If you have an internal method on a class which is a staticmethod, but it needs to behave differently in some subclass surely it is easiest to just namespace it? Rather than having to name each free function like: class_A_helper, subclass_B_helper, subclass_C_helper?
i think jason uses 2 space indents in his c++ series (only person i've seen do it)
good 🙂
but 2 in JS/Scala?? 🥴
I have used 2, but I've settled on 4 because that's what most other people use, and using what your team expects is important.
I just press tab and hope pycharm is configured 🤷
I guess I can think of one case where it might make sense? If you have an internal method on a class which is a staticmethod, but it needs to behave differently in some subclass surely it is easiest to just namespace it? Rather than having to name each free function like:
class_A_helper,subclass_B_helper,subclass_C_helper?
@safe hedge this is a good point, I think
but then again...is there a concrete example?
maybe a per class factory function?
Dunno, but as I say I've used them in some DB stuff where I modify records before entering depending on the DB
If it needs to behave differently in the subclass, then it shouldn't be a static method - the subclass's implementation might depend on member variables of that class.
Whether that was the right thing to do is another Q
And if it's a factory function, it should almost certainly be a classmethod, not a staticmethod.
a classmethod gets the class as an argument.
@safe hedge Like this?
if db == "postgresql":
...
elif db == "sqlite":
...
Effectively. But I just have classes that I use for DB interaction
Well, that's one way to do architecture 🙂
there's a classmethod-vs-staticmethod example I copy and paste when explaining it
<#ot1-perplexing-regexing message>
a classmethod is the right thing to use for a factory function, because it gets the class that it was called on as an argument, which allows it to return a new instance of that class.
if you were to use a staticmethod instead, then if you subclassed the class containing that staticmethod and called it, you would still get an instance of the parent class, rather than the child class: it wouldn't know that it had been called on the subclass (and should therefore return an instance of the subclass)
can this not unpack int()?
for key, value in scores.values():
print(f"\n Computer : {key}")
print(f"\t You :{value}")
if this question is not suited for this channel pls tell me so
ok
it isn't suited for this channel, but there is nothing wrong with your code just by looking at it, assuming scores is a dict
ok thx
values() only returns a single value, you should be using items
i got it thx
oh woops
for what
Hey guys, Is machine learning and the fields of AI overhyped and over saturated? Will it still be the hottest job in the future like 2020-2040? I see everyone taking ML courses, reading books and getting a job. Is ML that easy? Will it still remain the most indemand jobs in the future?
@grand ibex Hey guys, Is machine learning and the fields of AI overhyped and over saturated? No it's not
Will it still be the hottest job in the future like 2020-2040? No one can predict the future acuratly but as things are looking now YES it is going to play a big part
I see everyone taking ML courses, reading books and getting a job. Is ML that easy?
No it is not easy to learn in debt but anyone can learn the basic surface of it
Will it still remain the most indemand jobs in the future?
Most likely yes
I disagree with all of those :P
Unless something radical happens with explainable ML models, the fundamental problem is that ML is a black box. Lots and lots of business rules need to be able to answer the simple question "why did the system do this?" Might even be a legal problem if you can't.
while explainability is a real problem, it isn't entirely blocking for most companies, ML is used in finance, energy, ecology, defense, and many other fields and there's no reason it would stop all of a sudden
let alone for companies that use ML for more "mundane" tasks
Sure. But it's also not clear that there's a growth in demand that is going to outstrip supply for all time. Just like with programming it didn't actually turn out to be a career where the value of the programmer was slashed when there were enough of us (there never was), or when everyone could do their programming themselves (never happened).
ML is going to be useful for the foreseeable future for sure, but if the talent pool is the same as for regular programmers (which is seems like), it would seem like both ML arborists and regular old programmers can still enjoy great salaries for a long time to come.
Depends on what "most in demand" means I guess...
In Stockholm programmer is the most common job. That's one way to say "most in demand"... but that's not a very useful metric imo.
this is offtopic for this channel in anycase, try #career-advice
this isn't a help channel
please see #❓|how-to-get-help
@unkempt rock thanks for the answer!
class RandomGenerator:
""" The base class for all random markdown generators """
file_name: str
output_dir: str
output_size: int
def __init__(self,
file_name=None,
output_size=None,
output_dir='.'):
self.file_name = file_name
self.output_size = output_size
self.output_dir = output_dir
Here, I want to raise an error if file_name is not provided (or set to None) during class initialization. Which method should I use? I was thinking __getattr__ but I am not really sure.
Or should I use a try..except block in __init__ itself?
I'm not quite sure what you mean; what's stopping you from checking if the parameter file_name is assigned to None and then raising an exception?
You could also just make it a mandatory argument by not providing a default
I'm not quite sure what you mean; what's stopping you from checking if the parameter
file_nameis assigned toNoneand then raising an exception?
@wide shuttle My question was, where do I check it. In the__init__? And using what method? I was thinkingtry..exceptbut idk
You could also just make it a mandatory argument by not providing a default
@wide shuttle That is a good solution
But if I needed to check for some different condition, where would I do that?
if i have multiple columns with a single letter in one dataframe, and another dataframe has a weight for each letter, how do I multiply the weights?
do you guys play wow? just wondering
This channel is specifically meant to discuss Python itself, from a higher-level and more abstract perspective. For WoW, I'd recommend an offtopic channel. (There are three of them just below in the offtopic/general category.)
@covert saddle why are you making the parameter optional then making it required also? That's just confusing.
@half wolf I was wrong there, so I fixed it
Raising exceptions from the constructor is perfectly fine.
So __init__ would be okay place to raise exception?
Absolutely. This isn't C++. Python is much more sane :)
I love that xD
Python isn't much different than C++ here, actually... It's sane to raise an exception from a constructor in both, and it's not safe to raise an exception from the destructor in either
Though Python handles it more sanely if you do.
@raven ridge I thought raising an exception in __del__ just gets suppressed
though I guess that results in unsafe behavior
if your __del__ calls something and you need exceptions it raises to be handled.
(even if you're not raising one right in the __del__)
del is a bit special, have yet to see it used anywhere with all the special cases around it
I've never used it
Maybe it should've been called __on_garbage_collection__?
Because __del__ suggests that it's a hook for del somehow
yeah, that's what I thought at first
but searching it up made it clear that it means __on_garbage_collection__
@raven ridge so are my destructors implicitly noexcept?
@raven ridge I thought raising an exception in
__del__just gets suppressed
@boreal umbra printed to stderr and suppressed, yes - which is saner than the C++ behavior of just aborting the program.
@raven ridge so are my destructors implicitly
noexcept?
@red solar https://docs.python.org/3/reference/datamodel.html#object.__del__ - yeah.
Warning
Due to the precarious circumstances under which
__del__()methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead
i meant more in c++
somehow i'm more familiar with implementing del in C, than C++ destructors :/
In modern C++ destructors default to noexcept, yes.
The point I'm making is just that both languages face exactly the same problem and handle it in roughly the same way.
C++ is less friendly about it, just terminating your program, but both say it's the user's responsibility to prevent a destructor from throwing.
How can I have optional dependencies for my package? For example in django, unless you use models.ImageField, you don't need to have PIL installed.
If I write a module using that optional dependency, do I need to write it separately to prevent any ImportError?
use extras_require @covert saddle
example:
extras_require = {
'voice': ['PyNaCl==1.3.0'],
'docs': [
'sphinx==1.8.5',
'sphinxcontrib_trio==1.1.1',
'sphinxcontrib-websupport',
]
}
Where? I am using poetry package manager to build and publish my package
oh okay.
If I write a module using that optional dependency, do I need to write it separately to prevent any
ImportError?
What about this?
If you want to make sure it doesn't cause an ImportError then yes you need to make sure you structure it in the correct way
For example:
pkg
- __init__.py
- subpkg
- __init__.py
- module.py
- subpkg_that_has_optional
- __init__.py
- module.py
Now if you were to put import subpkg_that_has_optional or from subpkg_that_has_optional in your top-level __init__.py then any time you try to import that package at all you'll get an ImportError if the optional thing isn't installed
@covert saddle
@safe hedge okay, so i shouldn't be importing subpkg_that_has_optional in my top level __init__.py, right?
@covert saddle you need to put some import statements either inside functions and/or inside try/except ImportError blocks.
Well it depends right
You can just not import them at all in the __init__.py
And then the users have to explicitly import those subpackages?
And that way the import error should only occur if someone is explicitly trying to import the module that uses optional stuff
Or you could do something like:
try:
import module_with_optional
except ImportError:
pass
in your __init__.py so that the module with optional stuff is made available simply by importing the top-level package if the optional module can be imported
okay thanks @WelshWizard#1004 @boxed#9332
Can someone tell me if Test Driven Development (TDD) is actually used in the industry? Is it a good idea to approach a new project using TDD?
yes to both
@covert saddle In my career I've used TDD as one tool among many. It makes more sense to use in some contexts than in others. If you can formulate your problem in terms of input and output and you have a clear idea of what you want your code to do, but not necessarily exactly how to do it, I think TDD really shines.
Hello, can I consult here for best practices for my project? I doesn't consists of only python though.
How much do I have to worry about backwards compatibility when writing a new package? I am using a lot of f-strings which will not work in python 2.7
Do people still use python 2.7?
I don’t think so
So I don't have to worry?
Well, we do at my employer.
We're unable to upgrade due to being stuck between market constraints and not having a good migration path.
But since 2.7 reached eol, you probably shouldn't bother accounting for such cases.
It's our problem, not yours.
hmm okay thanks for the advise
Okay here I go. I have developed a SaaS product for our company. I'm at the back end and I use python, mongodb and flask. On the front, angular is being used.
Our product consists of a dashboard and couple of other tabs to present the data. It mainly focuses on text processing and making insights from text data. In dashboard, it has many charts, summaries etc.
For now it works. But I'm not sure if I made it with using best practices. Now, whenever a user opens the site (dashbord), calculations are being made for many different charts. I'm saving some of the charts to cache (simply a local file) and re-use it if it haven't requested recently. What is this kind of application's best practice? Which tools and methods I can use for both maintaining and not to use redundant re-calculations? Text processing is sometimes an expensive process. Sorry if here is the wrong place to ask this or the question is too broad, but I don't know anywhere else to ask.
@covert saddle You should never have to worry about backwards compatibility unless you want to support it. You just have it so that your package is limited to specific versions and they'd need to use the matching version of Python to use your package. f-strings came in at 3.6 so you can support that and up. If you want to support <=3.5 you'd have to use .format
f-strings are much better than .format imo, but I do agree to what you say @languid dagger
iirc I'm starting to see newer versions of open-source libs dropping support for Python 3.5
@covert saddle also think about the passage of time. Say you write a package today: first there are some pretty big odds no one will care at all (yea that sucks) so then don't care about old python versions! Then if people do it will take a long time for the word to get around, again meaning by the time your lib is actually popular the definition of "old" will be different.
The smaller the lib, the more aggressive you should be in dropping old python versions.
"Small" is in popular/widely used.
okay thanks @half wolf that was really helpful advise!
I made my first package today
Sorry for asking questions in installments, but I am asking them as they come up in mind.
the more aggressive you should be in dropping old python versions.
Does this mean I don't need to use tools liketoxat all? Willpytestandflake8suffice in testing my package? @half wolf
@covert saddle I would think so. tox can be useful for running inside travis or whatever too probably though. And you might want to support multiple versions at some point.
okay and thanks again
ok
f-strings are much better than
.formatimo, but I do agree to what you say @languid dagger
@covert saddle I seem to find myself repeating this a lot lately.f-stringsare NOT a 1-to-1 replacement forformateven in 3.6+
Well, of course; there are cases where 1) format is more concise (like when accessing a lot of self's attributes; 2) you need to pass a template
@safe hedge did you have other cases?
- when the expression includes a backslash, maybe?
but in that case it's probably better to extract the expression into a variable anyway
3 is particularly annoying imo
I regularly want to do something like f"Some content \n{'\n'.join(somelist)} somemorecontent {variable}" etc
chr(10).join(somelist) 😄
I just find that too many people seem to think .format is totally dead
I certainly did, since I have never seem to use them after I discovered f strings
In general it might even be true. But at some point someone may come across a problem with f-strings and not understand they need to drop back to .format. I think it's important to make the distinction between them.
Ha
that part of the Zen is pretty much in ruins
@safe hedge i think the people who think format is dead are the people who only ever used format in ways that can now become f-strings (and should).
Let's not forget that you should still use % formatting for logging too.
String formatting: not even once
Let's not forget that you should still use
%formatting for logging too.
@safe hedge I am split on this
on one hand, yes, efficiency, etc.
on the other, readability counts, and as long as you're not logging a lot in a tight loop...
you don't have to tho, you can change the style
but you know what we really need?
I quite like it tbh because it makes it really easy for me to spot which strings are for logging at a glance
can anyone help me with this plz
you don't have to tho, you can change the style
@teal yacht You can change the%to something else, but it's still old-style formatting
You don't do .format or f-strings in logging for efficiency
@fathom tusk try #❓|how-to-get-help
@gleaming rover you are really dipping deep into cs history with "call by name"
but if u get an answer lmk
@fathom tusk I know how to solve it, it's a p basic question
but it is also off-topic for this channel
the only "old-style" thing is the %, not how the arguments are evaluated and added to the string
if you use {} it's no longer "old-style"
@gleaming rover you are really dipping deep into cs history with "call by name"
@spark magnet well...
dm me the answers? @gleaming rover would be greatly appreciated =]
I had to Google it to make sure I had the name right
algol, right?
scala does that?
I wasn't even close to being born when ALGOL was invented
in fact, I don't even think my parents were born
you could still know about it 🙂
dm me the answers? @gleaming rover would be greatly appreciated =]
@fathom tusk that looks like homework and is something you could probably solve yourself. do a little Googling.
why would you want that tho @gleaming rover ?
scala does that?
@spark magnet what I understand by "call-by-name", in the way Scala uses it, is an argument passing strategy where unevaluated expressions are passed
and they are only evaluated as needed
right, like macros
why would you want that tho @gleaming rover ?
@teal yacht it was facetious
to solve the problem of logging inefficiency
people have macro things for python
only evaluate the expressions if the logging call is actually needed
it's kinda impossible to know if a logging call is needed tho
unless you meant the flushing part i guess
a thing people often overlook when proposing new features for python is that each file is compiled separately, with no information from the imported files.
@teal yacht Ok. Let's call it a 3rd style then.
it's kinda impossible to know if a logging call is needed tho
@teal yacht what do you mean
how do you decide whether or not a log will be needed ?
we delay string interpolating in logging libraries because IO is expensive, to do it in batches, and strings are more expensive than references to objects
i don't understand that last point
how do you decide whether or not a log will be needed ?
@teal yacht logging level?
ah yeah i guess i forgot about that point
yeah so like logging is built the way it is to delay string interpolation, right
it's kinda impossible to know if a logging call is needed tho
@teal yacht it's to only format the message if the log record passes the filters.
but the arguments are still evaluated
@spark magnet we don't do log("%s" % obj), we do log("%s", obj)
Evaluated but not interpolated
so call-by-name (which I am not seriously suggesting, just for this), would also delay the evaluation of arguments
Evaluated but not interpolated
@raven ridge yes, so in a case where it is the evaluation that is expensive, whatloggingdoes wouldn't help
So today we save some of the cost, this would save more of the cost.
it wouldn't really bring many benefits i'm sure, an ast node is surely more expensive than most cases where we get just another reference
What about log(lambda: "%s" % obj)? 🙂
precisely
@grave jolt have you not ruined enough lives with chr(10).join
(honestly I thought of that too but you were quicker)
@teal yacht i see, you meant we save the cost of the formatting
@teal yacht ast nodes are not relevant here, the compilation only happens once
it wouldn't really bring many benefits i'm sure, an ast node is surely more expensive than most cases where we get just another reference
@teal yacht I don't think there are many cases where it would be better, which is why I said it was a joke
yeah, we don't want to store large strings for long durations, as we can't predict when the logger will actually flush
@gleaming rover the problem isn't adding another strategy, it's adding a second strategy, with no way to know when to use which one.
they literally added an operator for matching regexes in while loops so
with no way to know when to use which one.
@spark magnet what do you mean by this part?
that was for readability.
@gleaming rover how would Python know whether an argument was by-name or not?
function definition
this is what i mean: when the call is compiled, the func def isn't around.
lisp does it just fine tbh
obviously you'd need a way to represent the ast in a sane way, and an alternative way to define macros/call-by-name functions
that was for readability.
@spark magnet for deduplication, really. The loop-and-a-half examples were really the convincing ones, I think
i think you quoted the wrong line, but yes.
yes, I did. stupid mobile 🙂
hm I don't have enough knowledge to put what I'm thinking in the right terms
@teal yacht my point is that the compiler would need to know for each function call what the function definition said to do with the args.
yes, what would be the issue with that ?
the compiler doesn't examine the imported files
lisps do it just fine, and there exists many many lisp dialects, running on different internal mechanism
you can add it to the function object
the compiler doesn't have the function object
at the call site the caller knows what it's calling
really instead of having <function object at xxx> you'd have <macro object at xxx>
but the compiler has already reduced the expressions to bytecode
so now everything is a macro?
cmd = input("Enter a command or 'quit':")
while cmd != 'quit':
process(cmd)
cmd = input("Enter a command or 'quit':")
^ Code like this is the compelling argument in favor of the walrus. Because the alternative without the walrus is usually something much uglier, like:
cmd = None
while cmd is not None and cmd != 'quit':
if cmd is not None:
process(cmd)
cmd = input("Enter a command or 'quit':")
And with the walrus it's the much nicer:
while (cmd := input("Enter a command or 'quit':")) != "quit":
process(cmd)
macros inherently require a preprocessing step, so yeah
and they require having the source of the imported modules?
why the source ?
import foo
foo.bar(x)
ok, not the source, but you have to have the code in some form.
in order to do what you're proposing, Python would need to generate different bytecode depending on whether foo.bar() is pass-by-name or pass-by-object-reference
and at the point where it generates the bytecode, it has no idea what bar is, or whether bar exists - it's even entirely possible that bar doesn't exist yet but will later.
exactly
i mean, yeah, that's because python is dumb
we could rework things out
in this very hypothetical unreasonable unwanted scenario where macros get added to python
if you change something as fundamental as that, you get a completely different language.
i'd say it wouldn't be a bad thing 🙃
get a discord for your new language. 😛
seriously, whether such a hypothetical language would be better or not aside, there's no way to evolve Python from where it is today to that, considering backwards compatibility.
python 5
Please support I need tea https://www.patreon.com/tsoding
that said, it would be possible to make a lazy-evaluation operator, I think. So that you can do py logger.info("%s", lazy fib(100)) and it will pass a new LazyExpression object with a .get_value() method, and where the expression isn't evaluated until get_value() is called on it.
that'd be strictly equal to wrapping into a lambda tho, except it's slightly more obvious
right - syntactic sugar over that.
Python as a language is syntactic sugar really though right
what does that mean?
The whole point is that stuff is concise and simple to do with fairly obvious names
isn't every language in that sense sugar?
So syntactic sugar in python is kind of the point
what's the difference between "syntactic sugar" and "syntax"?
foo.x is syntactic sugar for getattr(foo, 'x'), which is syntactic sugar for foo.__getattr__(foo, 'x') when foo is an object. Syntactic sugar is very powerful for guiding people towards usage that you want to encourage and away from usage that you want to discourage.
I was merely trying to express that introducing something that was syntactic sugar around lambda like lazy would be pretty on-brand for python
actually i think a new way to write a lambda would never be accepted, because it dosn't add anything new
what's the difference between "syntactic sugar" and "syntax"?
@spark magnet I'll take a stab at this: "syntactic sugar" is introducing new syntax to make an operation that was already possible using existing primitives easier.
not all new syntax is sugar, but all sugar is new syntax.
is multiplication syntactic sugar for repeated addition?
Yes
no, it isn't.
I don't think it is
it has different semantics.
they're functionally different
is the walrus operator syntactic sugar?
foo.xis syntactic sugar forgetattr(foo, 'x'), which is syntactic sugar forfoo.__getattr__(foo, 'x')
andfoo.__getattr__(foo, 'x')is syntactic sugar forgetattr(foo, "__getattr__")(foo, 'x')... you get the idea 🙂
but a*b is syntactic sugar. You could do what it does without it:
res = type(a).__mul__(a, b)
if res is NotImplemented:
res = type(b).__mul__(b, a)
if res is NotImplemented:
raise ...
2 * 4 = 2 + 2 + 2 + 2
i think lot a lot of software terms, it's used like it's black/white, but it's really fuzzy
but
a*bis syntactic sugar. You could do what it does without it:res = type(a).__mul__(a, b) if res is NotImplemented: res = type(b).__mul__(b, a) if res is NotImplemented: raise ...
@raven ridge isn't there a subclass check
like compiled vs interpreted? @spark magnet
yes 🙂
Simple multiplication is definitely just multiple additions in disguise
Simple multiplication is definitely just multiple additions in disguise
@safe hedge mathematically, yes
@safe hedge how can it be syntactic sugar if it results in different i386 instructions?
Oh I thought you meant mathematically
even mathematically
2 * 4 = 2 + 2 + 2 + 2
@safe hedge
In [41]: .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1
Out[41]: 0.9999999999999999
In [42]: .1 * 10
Out[42]: 1.0
and that's only for Nat * Nat
@teal yacht okay, fine
@raven ridge isn't there a subclass check
@gleaming rover Don't think so - what would the check do?
I did qualify it to "simple" multiplication
I did have a mistake there, though - type(b).__mul__ should be type(b).__rmul__
@gleaming rover Don't think so - what would the check do?
@raven ridge ah, never mind, it doesn't apply to__mul__
my mistake
a language's data model and execution model determines what operations it allows. A language's choice of syntactic sugar determines what operations it encourages.
When I protested that f-strings != .format I did not expect to end up here 😆
#internals-and-peps is just #esoteric-python without code
if Python didn't allow attribute lookup with a.x, the fact that attributes can be stored on any object would more likely be trivia than a fundamental feature relied upon constantly by everyone.
I would say that "syntax sugar" is something that can be transformed into "plain syntax" with a sort of preprocessing step, i.e. it's something that is exactly the same in all aspects. Like decorators:
@f
def g():
...
# exactly the same as:
def g():
...
g = f(g)
# except when you inspect the stack frame and stuff, but that doesn't count, really!
Or like do-notation in Haskell:
f = do
x <- hello "world"
y <- abc 'd'
z <- f x y
return (x, y, z)
-- exactly the same as:
f = hello "world" >>= (\x -> abc 'd' >>= (\y -> f x y >>= (\z -> (x, y, z))))
In Haskell there are many compilation steps, and on some point some syntax sugar is actually turned into simpler syntax along with other modifications.
In Python there isn't really such step, but I guess there could be
so in Python it's kind of vague
I agree, I'm just imagining that the "preprocessing step" is something that a human could do.
if you can get from (new syntax) to (existing syntax) via some mechanical transformation, and the (new syntax) is designed to be nicer to use than (existing syntax), then (new syntax) is syntactic sugar for (existing syntax)
regardless of whether the language itself has any sort of mechanism to enable that preprocessing step.
i guess the problem is "the step" has gradations of difficulty, and the before and after have gradations o fidelity.
Is yield from syntactic sugar for
_i = iter(EXPR)
try:
_y = next(_i)
except StopIteration as _e:
_r = _e.value
else:
while 1:
try:
_s = yield _y
except GeneratorExit as _e:
try:
_m = _i.close
except AttributeError:
pass
else:
_m()
raise _e
except BaseException as _e:
_x = sys.exc_info()
try:
_m = _i.throw
except AttributeError:
raise _e
else:
try:
_y = _m(*_x)
except StopIteration as _e:
_r = _e.value
break
else:
try:
if _s is None:
_y = next(_i)
else:
_y = _i.send(_s)
except StopIteration as _e:
_r = _e.value
break
RESULT = _r
```?
I'd argue that if it loses fidelity it's not sugar - it's only sugar if there's already a way to do exactly the same thing.
but I don't draw any such distinction for difficulty - whether it's a huge, involved, multi-step transformation to get from new to old, or it's a simple substitution, I'd call both of those sugar for the old syntax.
Is yield from syntactic sugar for
IMHO, yes. It's not something new in the data model, it's something that was always possible but that now has blessed and accessible syntax, encouraging its use.
(assuming you copied that from the yield from PEP, at least - I didn't actually read it, I just think that yield from is syntactic sugar for something, and that looks like it might be it 😆 )
class MyClass:
my_attr: str
def my_method(self):
pass
Is there any way that I can access the type-hint of my_attrwithin my_method?
self.__annotations__
If I have a module/pkg and I want to use it's string name (i.e. 'mypkg.module') and then also import it, is it a bad or OK idea to do something like the following:
from importlib import import_module
MY_MODULE = 'mypkg.mymodule'
def somefunc():
mods = [name for _, name, is_pkg in pkgutil.iter_modules([import_module(MY_MODULE).__path__[0]])]
The alternative would be to wither hardcode the name as a string where I use it or to use:
import mypkg.mymodule
def somefunc2():
do_stuff(mypkg.mymodule.__name__)
I like the last option best. It's succinct, and immediately obvious to the reader.
Or just use "mypkg.mymodule" instead of mypkg.mymodule.__name__
but if you really don't want it as a string literal, your last option seems nice to me.
It's more that if I were to change the path to the module then I could see having string representations hardcoded being a likely source of bugs
At least if I do mypkg.mymodule.__name__ and then changed the import to mypkg.mymodule.submodule or whatever there's going to be a very clear errort
self.__annotations__
@teal yacht ok thanks
You'd wind up find/replacing the module name, and it wouldn't be too tough to match the string at the same time.
but yeah, the __name__ approach is fine by me.
True I guess, thanks. I always feel uneasy using double underscore variables because I worry I've misunderstood what they'll be
Like I wasn't sure if __name__ would always return what I expected
As far as I know, it will. __name__ is always the name by which a module was imported, except for the initial module which is always named "__main__"
It depends what you mean by "the name by which it was imported" I guess. Because os.path returns posixpath which I guess could throw some people
I'm just going to go ahead and assume that would be a very bad idea
I've done it for things defined in private submodules and re-exported by their parent package... But mostly to work around the fact that Sphinx handles private submodules poorly.
lol
@left bronze I'm not quite sure what the relevance of that was for the channel. It looked more like advertisement than something that directly discussed the Python programming language itself.
Found the info, downloaded the image and shared over here
Not aware that sharing pic like the one is not allowed
@wide shuttle
I'll type it out next time onwards
It's more that this channel is for discussing the Python programming language itself, from a higher-level and more abstract perspective. The image that you shared seemed a bit random and did not relate to a discussion of Python itself as far as I can tell, @left bronze.
Oh ok
Got it
The image I shared was telling an alternative of pandas that helps in scalability
But cool, I'll keep it in mind before sharing
Probably would be something better suited to #data-science-and-ml
Does anyone have good explanation of how the ispkg value in ModuleInfo returned by pkgutil.iter_modules is calculated? I tried following the source code but I got a little lost at sys.path_importer_cache which is written in c
Yo would you guys know a way to reset a function
Need more details than that, maybe open a help channel #❓|how-to-get-help
class MyClass:
def my_method(arg1: str, arg2: int):
pass
Is this any way I can access the type hint of args1 and arg2 inside my_method?
I tried arg1.__annotations__ but it doesn't work
Well, why would the variable arg1__annotations__ be defined?
You can access my_method.__annotations__
arg1.__annotations__ can't possibly work: arg1 is a string and therefore is immutable
Annotations don't change anything at runtime, except appearing in __annotations__
ok thanks again
Is it possible to create my own cryptocurrency using python? lmao
Is there any way I can pass all the arguments to a new function without having to specify them explicitly?
For example:
def my_func(arg1, arg2, ...):
print("something here which will print the value of arg1, arg2 and the others without me having to specify them explicitly?")
Is there any way I can pass all the arguments to a new function without having to specify them explicitly?
For example:def my_func(arg1, arg2, ...): print("something here which will print the value of arg1, arg2 and the others without me having to specify them explicitly?")
@covert saddle if you have explicit parameter names, I don't think so
at least, not without some magic
yeah *args, **kwargs would have been easy but it's not the case here
if you're not using type hints, though, how about copy-paste? 🙂
wdym?
copy-paste the parameter names from the function signature 🤔
oh but I have to call this for a lot of fucntions. I was searching for something programmatic.
if you're not using type hints, though, how about copy-paste? 🙂
@gleaming rover What if I apply type hints to them?def my_func(arg1: str, arg2: int): pass. Would it be possible then?
no, if you're using type hints then you can't even copy-paste
anyway, I wouldn't recommend this, but...
>>> import inspect
>>> def f(a, b, c, *args, **kwargs):
... args = inspect.currentframe().f_locals
... print(args)
...
>>> f(1, 2, 3, 4, 5, f=6, g=7)
{'a': 1, 'b': 2, 'c': 3, 'args': (4, 5), 'kwargs': {'f': 6, 'g': 7}}
Well basically I am checking if all the values specified to a function are among a list of permitted values. If they are not, I am raising an error so that they don't misuse the function and fuck up their system. is there a better way of doing this than what I am trying to do?
are there patterns in the ranges of accepted values
if there are you could use a deco
>>> import inspect
>>> def f(a, b, c, *args, **kwargs):
... args = inspect.currentframe().f_locals
... print(args)
...
>>> f(1, 2, 3, 4, 5, f=6, g=7)
{'a': 1, 'b': 2, 'c': 3, 'args': (4, 5), 'kwargs': {'f': 6, 'g': 7}}
@gleaming rover Yeah I saw this on SO, but it said not recommended too
hard to say without knowing the details
but I think what you have is more an architecture problem than an implementation problem
I am not sure what that means
Can you just give the example code you have and what you are trying to do? Might be best in a help thread though
in other words, you're asking "how do I do this?", when you might need to ask "what should I change so I won't have to do this?"
the general thread or help-* one?
Can you just give the example code you have and what you are trying to do? Might be best in a help thread though
@safe hedge
is there a particular reason to do f_locals instead of just locals()
it's the same thing on the first line right
yeah, you're right
is there a particular reason to do f_locals instead of just
locals()
@merry pollen That also gives the values of variables inside the fuction, not just the arguments. I don't really require the non arguments variables.
locals().keys() ?
@covert saddle my thought process was that you would call it first
ohhh wait
you want to check before the function is run? basically?
boy do i have the code for you
yeah basically
@merry pollen That also gives the values of variables inside the fuction, not just the arguments. I don't really require the non arguments variables.
@covert saddle no, that's not the distinction
>>> def f(a, b, c, *args, **kwargs):
... h = 8
... print(locals())
... print(inspect.currentframe().f_locals)
...
>>> f(1, 2, 3, 4, 5, f=6, g=7)
{'a': 1, 'b': 2, 'c': 3, 'args': (4, 5), 'kwargs': {'f': 6, 'g': 7}, 'h': 8}
{'a': 1, 'b': 2, 'c': 3, 'args': (4, 5), 'kwargs': {'f': 6, 'g': 7}, 'h': 8}
Hmm they both do the same thing then. This is not what I want.
you need a decorator that will intercept arguments and check them with the decorated function's signature
you could also use a decorator to capture all arguments
if you want checking-before-function-evaluation
you need a decorator that will intercept arguments and check them with the decorated function's signature
@merry pollen yeah that'd be great
I mean a help- thread
I still think it's hard to know what is best for you without any code
this is like, perhaps an example of what you want
where it basically does a check that a certain set of the function's arguments are either all provided or none of them are provided
@safe hedge moved to #help-peanut
@opaque etherRead #❓|how-to-get-help . Then tag me when you claim a channel.
Hi
This is not a help channel, if you need help use #❓|how-to-get-help @void ocean
Is it possible to activate a mining program that mines bitcoin using python
No downloads needed, just code
and uses the cpu or gpu
I mean you could do anything just whether or not it's a good idea is another thing
Also not the channel for this
what is the hex representation of the LOAD_CONST bytecode as stored in a pyc file? Python 3.8.2
This isnt a help channel guys, its a discussion channel about the python language and its features
If youre trying to get help, #❓|how-to-get-help
I asked them to come to here since it was something specific about implementation
Apologies
what is the hex representation of the LOAD_CONST bytecode as stored in a pyc file? Python 3.8.2
that's a valid question for this channel.
@heady mauve It should be 64 hex, 100 dec, d ASCII
!e
import dis
print(dis.opname.index("LOAD_CONST"))
@last pollen :white_check_mark: Your eval job has completed with return code 0.
100
@last pollen got it, thanks!
when pyc files are compiled, do they contain a timestamp? I compiled the same source twice with pycompile and I found that bytes 08 and 09 were different. They were followed by three bytes which stayed constant. CPython 3.8.2 on Linux.
It does yeah
One of the things it checks is whether or not the file you're wanting to compile is newer than or was recently edited compared to your current .pyc file or if the file has changed
It's typically faster for it to just see "oh the source file had an edit at 5:30 and the compiled file was made at 5:15." I think that's how it works anyway
Now I'm second guessing myself
thanks!
Yeah I just can't remember if it's purely based on time or if it hashes the file as well
I would think hashing it and comparing would be costly
i got some quesions about tests is it suited for this channel
I think that'd be better for #unit-testing
what is the best practice for having environment variables in an application.
I have windows and i usually use the setx command
@worldly venture Can you unban The Python Teacher