#internals-and-peps
1 messages Β· Page 74 of 1
724865789341204480
Also I'm going to move this conversation to #ot1-perplexing-regexing as this really isn't the place to discuss this kind of stuff
@full jay FWIW CPython does compare the timestamp in the pyc file against the file modified timestamp given by the OS
Oh by the OS. Well then I'm confused as to what those two bytes represent then
If it just goes by the OS' timestamp
They compare them
If the source file (OS provided) timestamp is after the pyc file (written in the file) timestamp, then you have to recompile the code
The OS is asked for the timestamp of a .py file. If there is no .pyc file or if the timestamp stored in the .pyc file is older than the timestamp the OS returned for the .py file, then a new .pyc file is written, and the .py file's timestamp is stored in it
Ahhh, okay so it is stored internally by the .pyc
Okay, that's what I wasn't sure about
these days, .pyc files can also be based on hashes instead of timestamps
Whats the best Programming Language should I use to make a bitcoin wallet and other types of wallets?
guys why making my script executable mess up the working of it?
these days, .pyc files can also be based on hashes instead of timestamps
@spark magnet TIL
guys why making my script executable mess up the working of it?
@quartz abyss wild guess: you've given the script the same name as a module that you import from the script. Because the directory that you run the script from is implicitly added to the module search path, the import finds your script instead of the module you meant to import
I misread the question entirely, heh. I thought it was "why does changing the name of the script change the behavior". Oops π
hehe
:incoming_envelope: :ok_hand: applied mute to @strange aspen until 2020-09-23 22:26 (9 minutes and 59 seconds) (reason: role_mentions rule: sent 4 role mentions in 10s).
:incoming_envelope: :ok_hand: applied ban to @strange aspen permanently.
does anyone has any tips about where should i start to learn about factory automation with python? (not sure if this is the propper channel for this question but i'll give it a try)
i founded some videos about a guy named Jonas Neubert (very good by the way) but I was looking for something more like a book
If one does dir( ) on an object then it shows the attributes of that object, is something like str an attribute of something though?
when I do dir( ) without an object it returns the variables which are in memory π€
dir(__builtin__)
is probably what you need.
undefined for me actually π€
ooooo , ok - this is something i was wondering about the other day I think, or related to - why isn't __builtin__ defined in pdb session?
my previous question wasn't exactly that, but that's what I"ve just bumped into when trying to run the above, and I don't really understand what's going on there, or how I'd go about finding out
it might actually be an ipython thing, no idea if it's normally defined. π
Maybe __builtins__? And also I think you can import them.
no - __builtin__ works alright in a typical session, but not in a pdb... oh i see what you mean, i'll check
yeah - seems to be an ipython thing
__builtins__ does work though, this seems odd to me
so I guess ipython reexports __builtins__ under the name __builtin__ in addition to the normal one
I'm sure there was a reason for that at the time π
i don't think i like that, but I am not qualified to complain properly lol
@lucid oyster I founded the second edition of this book on my yesterday research but I was looking for something a little more specifig like modbus protocole and plc integration! This is a little generic.. like for automation of daily routines... But thanks man for your help
Hmm
https://www.youtube.com/watch?v=cEyVfiix1Lw&feature=emb_err_woyt if you are courious..
"Speaker: Jonas Neubert
In industrial automation tried and tested always beats latest and greatest: The machines that make smartphones have a serial port and are configured with .csv files. But when your factory automates complex non-linear workflows and is jam-packed w...
seems a nice field for python developers π
Interesting
My internet is setup in a way that it blocks the connection but try these two on pdfdrive, i cant open them atm
wow this seems exactly what i'm looking for !! nice brow
just not sure if it is python related
I am not sure about that sadly
Its a very niche field
He does PLC programming which is usually done by python
So its definitely related
i didn't opened it yeat, was just judging by the cover but i'm on my way to find out
Guys on r/Automate say that python is not really great for industrial automation
9 votes and 20 comments so far on Reddit
Soo yeah, Its not that advanced
Keep looking tho, there might be smthin
there's a lot related to raspberry and is kind of easy to use python on it. I think i'll start digging on it.. I really appreciate your effort on the researches π€
Is there a pattern for creating an api to commonize to different object interfaces?
@swift imp can you give an example?
There's bokeh figure objects and matplotlib figure objects
Want to create a single interface that abstract some common functionalities
I guess I can just use single dispatching
makes sense, unless you want to create a wrapper class, but it will still be single dispatch internally
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
hello every1
can anyone explain me what this code is:
def f(a, l[]):
l.append(a)
return l
f(1)
f(2)
print(f(3))
ok?
that doesn't look valid
Looks like it's missing an =
yeah or some weird c++ python lovechild
it looks absolutely nothing like C++ π
it's literally Python with 1 missing character.
!e
def f(a, l=[]):
l.append(a)
return l
f(1)
f(2)
print(f(3))
@flat gazelle :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3]
it probably demonstrates this once you correct it
The same thing in C++ would be:
#include <iostream>
#include <vector>
std::vector<int> default_l;
std::vector<int> f(int a, std::vector<int> & l = default_l)
{
l.push_back(a);
return l;
}
int main()
{
f(1);
f(2);
for (auto x : f(3)) {
std::cout << x << std::endl;
}
}
so - not very similar.
does it have the same behaviour?
yep, output is:
1
2
3
but it would be 3 if nt> & l had the & removed, right?
yes.
Does anyone know of a common library which uses the newer implicit namespace packaging style?
it's not really a "newer style"; it's just a new feature for the cases for you do want a namespace package. you just.. almost never actually want a namespace package
i m looking for some projects as a beginner send help
@safe hedge why do you ask?
I wanted to run some pkgutil stuff on one to see if it behaves like a normal package
Just interested really since I've been using pkgutil a lot trying to get this plugin thing working
it doesn't; namespace packages are an utter pain in general and don't really behave like normal packages
I could mock my own but I was being lazy
It's trivial to make your own... Easier than installing one, frankly. Create an empty directory, create a Python file in it. Done.
Mainly I want to know what happens if you import a namespace package and do __path__
What I just said is sufficient to test that. Though the PEP explains it in detail.
Basically, it behaves just like it used to with explicit namespace packages, but slightly better.
Hello from the pygame community. https://www.pygame.org/contribute.html
2020-09-24 12:08:16.346 Python[38515:2002322] ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to (null)
Unable to obtain graphics context for NSWindow (Mojave behavior)```
CAN SOMENE PLZ HELP
It's been a long day I didn't even think to read the PEP
@austere jewel you need to get a help channel for that #βο½how-to-get-help
!pep 420
Yeah I just took a look. Seems like __path__ would still be usable same as a non-namespace pkg
Except that it can contain more than one entry, yeah
And https://docs.python.org/3/reference/import.html#__path__ confirms that
https://docs.python.org/3/reference/import.html#package-path-rules explains it better (linked from the first one)
Hi
Do you guys think we can write a code to calculate space complexity of a python program
Like rather than looking at the code and figuring out the complexity
A program that looks at the code and calculate complexity
I am pretty sure you will run into the halting problem
It may be possible with something like agda's enforced total functions
You might get somewhat there by using something that figures out the McCabe complexity. Flake8 provides that out of the box.
Except that it can contain more than one entry, yeah
@raven ridge__path__returns an iterable anyway though, and for what I have been doing you can just pass__path__intopkgutil.iter_modulessince it takes an iterable
I am pretty sure you will run into the halting problem
@flat gazelle This, finding complexity of arbitrary programs, whether it is space or time is undecidable
cyclomatic complexity is also very unrelated to computational complexity, it's (or its usefulness rather) actually closer to psychology than to computer science
for arbitrary programs, yes
rock_dir = os.path.join('/tmp/rps/rock')
paper_dir = os.path.join('/tmp/rps/paper')
scissors_dir = os.path.join('/tmp/rps/scissors')
What is the use of os.path.join in these situations?
I think this would be just as fine:-
rock_dir = '/tmp/rps/rock'
it does nothing in your code @rugged shadow
def createFolder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print ('Error: Creating directory. ' + directory)
# Example
createFolder('.\\'+ str(guild.id) +'\\')
``` I'm runin this, but it isn't working
You should take a look at #βο½how-to-get-help
def foo.bar(hello):
print("world")
def foo["bar"].baz(hello):
print("world")
instead of
def _foo_bar(hello):
print("world")
foo.bar = _foo_bar
def _foo_bar_baz(hello):
print("world")
foo["bar"].baz = _foo_bar_baz
Tolerable or outrageous?
def System.out.println():
``` ^ outrageous π
I want to be outraged but am not
well, you can already do this π
@myobj.setattr(foo, "bar")
def _foo_bar(hello):
print("world")
and maybe you could do a decorator like this
@F.foo["bar"].baz
def _(hello):
print("world")
that would do stuff with frames
I have created a registration page, and I need a unique id in it
This is the requirement -
Unique Id :- it would be a six digit alpha numeric combination unique if it isnβt entered by the
user it would be auto generated from backend.
And I have created this registration page using django.. Can anyone help, please?
wrong channel @modest pumice
Sorry!
def foo.bar(hello): print("world") def foo["bar"].baz(hello): print("world")instead of
def _foo_bar(hello): print("world") foo.bar = _foo_bar def _foo_bar_baz(hello): print("world") foo["bar"].baz = _foo_bar_bazTolerable or outrageous?
@grave jolt I can't get behind this because it means the names of functions now have to be evaluated as expressions
can someone help me create a discord bot??
def foo.bar(hello): print("world") def foo["bar"].baz(hello): print("world")instead of
def _foo_bar(hello): print("world") foo.bar = _foo_bar def _foo_bar_baz(hello): print("world") foo["bar"].baz = _foo_bar_bazTolerable or outrageous?
@grave jolt
@partial(foo.__setattr__, "bar")
def _(who):
print("hello ", who)
uh... no, thanks
that's more like #esoteric-python
@boreal umbra What do you mean? The names will be something like 'foo.bar' and 'foo["bar"].baz'
@grave jolt if the line def foo.bar(...): has the effect of making bar an attribute of foo
then the name of the function is being evaluated
yeah what about def foo.findChild("bar")[0].baz()
currently naming a function is basically the same as naming a variable, I believe.
@boreal umbra I don't understand what you mean and why that's a problem.
A function can have any name whatsoever, and it's assigned at the time of creating the function
!e
import dis
def f():
def g():
pass
return g
dis.dis(f)
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
001 | 4 0 LOAD_CONST 1 (<code object g at 0x7ff549a2dc90, file "<string>", line 4>)
002 | 2 LOAD_CONST 2 ('f.<locals>.g')
003 | 4 MAKE_FUNCTION 0
004 | 6 STORE_FAST 0 (g)
005 |
006 | 6 8 LOAD_FAST 0 (g)
007 | 10 RETURN_VALUE
008 |
009 | Disassembly of <code object g at 0x7ff549a2dc90, file "<string>", line 4>:
010 | 5 0 LOAD_CONST 0 (None)
011 | 2 RETURN_VALUE
So the name can be computed at runtime, but, well, it could be just static like 'foo.bar'
but if naming the function foo.bar does something other than just naming the function, now that can cause errors
right?
wouldn't you get a name error if foo isn't in that namespace?
can someone help me create a discord bot
@unkempt rock This is not a help channel. See #βο½how-to-get-help
what do you guys do here
@boreal umbra
def foo.bar(hello):
print("world")
will be roughly the same as
def _foo_bar(hello):
print("world")
_foo_bar.__name__ = "foo.bar"
# or, alternatively:
_boo_bar.__name__ = repr(foo) + ".bar"
# (doesn't really matter)
foo.bar = _foo_bar
well... yeah, you will get an error if foo is not found, why is that a problem?
@unkempt rock this channel is about in-depth discussions about Python itself
@grave jolt it's not a problem if you're okay with that being possible, but the only type of error you can get when you name something is if you use an illegal character in the name (or start with a numeric character, I guess)
and I would want naming functions and classes to be the same way.
I mean, if foo is not found you will get an error either way π€·ββοΈ
but giving the function to foo after the fact is a different kind of expression than just naming the function
Well, my proposal is just syntax sugar for defining a function and assigning it as an attribute
I see where you're coming from
I don't think it really needs to be added to Python (that's kind of a rare scenario), just a thought
fair enough
I wouldn't want to encourage people to retroactively add methods to classes
even though I think it's cool that you technically can
I don't think it really needs to be added to Python (that's kind of a rare scenario), just a thought
It's usually done as a decorator like this when it's needed:
@app.post("/users")
to me that makes it clear that the function being defined is being used in someone's API, or something along those lines
but I guess there's no reason why that's better for that than the syntax you've proposed.
Adding methods to classes van be great, if the language is made for it. Python is not :(
@grave jolt multi line lambda would be better probably.
I mean, type(thing).method = function is fine, though with some footnotes
*<Something>.prototype.<method> = ... flashbacks*
It's not fine at all. The problem is that import order is such a mess. There's no reasonable way to set up all such modifications before your main program starts imo.
In objective c and swift this works great and is well defined.
JS would say otherwise :P
Well, my idea was more about assigning functions as attributes to objects, like
async def bot.on_message(ctx, message):
...
there are definitely cases where you do not want both the function name and the decorator name
well, yes, when the name gets expected, for example
methods change between development mode and prod mode for us so things like on_ready events have to be dynamically done
@unkempt rock #discord-bots
@unkempt rock This is not a help channel, it's a discussion channel. See #βο½how-to-get-help or, well, yes, #discord-bots
and decorators have more flexibility, like keyword arguments (however, I think there's a proposal, to allow kwargs in indexing?)
i feel like it could be useful but would probably create way more confusing things than it solves
the option would be nice though
especially useful for something like pandas
# cool
@app.post("/users", response_model=User)
def register_user(
username: str = Body(...),
email: str = Body(...),
password: str = Body(...)
):
...
# this could work, but the name isn't inspectable
# (FastAPI actually does inspect it, and it puts it in `openapi.json`)
def app["post", response_model=User](
username: str = Body(...),
email: str = Body(...),
password: str = Body(...)
):
...
# well... maybe... but... meh
def app["post"]["response_model", User](
username: str = Body(...),
email: str = Body(...),
password: str = Body(...)
):
...
oh yikes no
thanks
yo this a decent place to ask a kinda snaggletoothed nginx/flask/swagger thing?
i figure it's a bit above posting in #web-development
nvm, just saw the "it's not a help channel" bit, my b
I asked a question in the help channels and I was instructed to ask here, in case there is a more obscure way to deal with the issue than the obvious ones.
I have created a function which takes a dictionary as an input. Inside the function the dictionary is gradually becoming empty and as I became painfully aware, when this happens the dictionary will remain empty forever since its mutable.
The problem is that I need to call the function more than 1 times with the same dictionary. I know i can create copies of the dictionary but I might have to do thousands of function calls using this dictionary.
I did finally, everytime I called the function, create a copy of the dictionary inside the function and work with the copy, so that the original remains unchanged. This pretty much solved the issue but Im talking about thousands of function calls here, so this copy() command might take some time overall
I was wondering, therefore, if there is a more advanced way to do something here. Thanks in advance. If anyone wants me to post the code or anything let me know. I dont post it beforehand in order not to cluster the chat
can someone help me with my python
@next falcon just use .copy() its implemented in C and def wont cause any huge issues with your code unless your talking a dictionary with 100k+ items
trust me the python is taking longer
Well, largest dictionary will have 60k keys, and each value is another dictionary, albeit with less keys hehe
Perhaps you're familiar with the topic, I just want to pretend its an adjacency list. I try to implement dijkstras algorithm but for an immense graph.
id still say just use .copy()
Ok, I will just pass the dictionary in the function then but work with its copy every time. Thanks chilaxan
or don't mutate the dict and you don't have to copy it
^ thats also an option
hey guys i have 50/50 odds of winnin/losing, how do i calculate odds of winning/losing multiple times in a row
thats not what this channel is about really
ok
and thats just basic probability
can u help?
im about to sleep
ok
@unborn raven read #βο½how-to-get-help for info on how to get help
@deft pagoda I am sorry for the ping, I just saw your message. Can you explain what yo mean "dont mutate"? I have to work on it so its going to be changed, am I wrong?
you shouldn't need to modify the dict for djikstra's
Oh ok. The way Im doing it is to, in every round you find the minimum path to a node, so you remove the node from the graph
There are better implementations i guess. This one is too slow as well sadly
For a graph of 60k nodes, it took me 5 minutes :/
oh, now i have a set of unseen nodes
Ah, its expected? Thats good to know.
I'll try your suggestion, modify the code to use a set of seen nodes so I dont have to mutate the initial graph.
i mean, you can time networkx's algorithm vs yours
Although the copy() command probably doesnt take 1 second even.
will probably be on the same order of time
I wasnt aware of this module. Might try it. Thanks
Thank you π
how do public apps hide api keys while letting the app users use the app?
I am using the imgur api to upload images
Is it ok to give all the clients the client ID and client secret?
"client ID" and "client secret" are just authentication information for you your account.
Like username and password.
So it's fine to give them to everyone?
Well, each user of an API has their own API credentials, just like they have their own password and username (how else would you authenticate yourself?)
Anyway, this isn't really on topic for this channel
They don't have their own client ID and client secret
You obtain them by registering your app
Your app is the user of the imgur API.
Just like @fallen slate is the user of Discord API.
Anyway, this isn't really on topic for this channel
Is it okay to give it away to them?
Although the copy() command probably doesnt take 1 second even.
@next falcon Since your dict is a dict of dicts be careful you don't need to usedeepcopyinstead.copywill just create a shallow copy and I think those nested dicts will just be references to the originals. That may or may not be a problem and you'll need to test that I suspect
yeah shallow copy just references the original one but deepcopy will copy the data into the new variable without any references
well, into a new variable without any references to the original one.
After import copy a = {"x": [1]} b = copy.copy(a) the items a["x"] and b["x"] are references to the same list.
After import copy a = {"x": [1]} b = copy.deepcopy(a) the items a["x"] and b["x"] are references to different lists with the same contents.
Hi all, Iβm not having much luck on the general channel. Iβm hoping to get some help with my code, https://mystb.in/IngCitizenshipRemainder.python how can I call the function find_all_entries within the βfor thingβ loop? Thatβs where I must be going wrong? I want to process each posts response for the json then post the next entry. How can I do this? Can someone help me please? Thank you
@wispy plover this would be a good question for a help channel. see #βο½how-to-get-help
@paper echo ahh thank you so much
Thoughts on:
(int, int) # Tuple[int, int]
(int, ...) # Tuple[int, ...]
[int] # List[int]
```?
in what respect?
As a replacement for current type annotation syntax
I don't really like it. It breaks consistency with other type annotations. There isn't room to come up with such syntax for all types.
I imagine it will visually be easily confused for actual tuples/lists
At least at a glance
I think unions and product types should have first class syntax support for sure, not sure about that list one tho, never been a fan
we discussed int | bool | T before as well
for Union[int, bool, T]
we could even stay consistent, as in use binary operators that we can overload, and use ML syntax and use * for tuples
giving int * bool * T == Tuple[int, bool, T]
I think I'd prefer (int | None) over Optional[int] now that you mention it...
union syntax seems nice
Or even or for that matter
Not sure about the *
* wouldn't actually be consistent because tuples are arrays in python, not actual product types
that feels more like a technicality than something that would matter
no because the fact that the 1-uple exists breaks stuff
ah :/
i wanna say this makes me uneasy, but idk why, or how to express it (pure's suggestion)
what does this mean?
enumerate(zip(*lst))
I think I know what enumerate is. ['s', 'a', 'b'] would be 0, s/ 1, a/ 2, b
zip(*lst) transposes the given list
i feel stupid idk what that means
zip( [1,2], [a,b] ) = [ (1,a), (2,b) ]
is that right?
yes
It "flips" a list diagonally e.g.
x = [ (1, 2)
, (3, 4)
, (5, 6)
]
# becomes
y = [ (1, 3, 5)
, (2, 4, 6)
]
```Terrible formatting, but yes
oh
reminds me of matrix transposition in lin-alg
i didn't think u meant that when u said transpose
yes that's exactly the same transpose
Pretty useful pattern when undoing a xys = zip(xs, ys)
xs = [1, 2, 3]
foo(*xs)
# same as
foo(1, 2, 3)```
it's called unpacking or a starred expression
so it turns it from a list to
that
idk what to call that
['hello', 'hey', 'ok'] = 'hello', 'hey', 'ok'
it unpacks it, there's no syntactical structure that holds it
yea so
hence why you were getting errors
you could use that as 3 parameters
zip takes N parameters
yes but like
those were lists in itself
but this is just parameters of a bunch of strings then
you can zip strings too
you are transposing the list of strings, not the strings themselves, you are zipping the strings
would like
'hello' = ['h', 'e', 'l', 'l', 'o'] basically be the same in this context?
because both can take [0] as a argument
indice the same
yes, in this context both are the same
try it with a small example input really, it'll be more obvious
yes, or the longer ones will truncated up to the length of the smallest one
it's an implementation detail of zip
there's zip_longest in itertools, which doesn't truncate
zip(βflowerβ, βflowβ)
{
f l o w e r
f l o w
}
=
ff ll oo ww
is this correct?
yes
can i ask about decorators here?
ive been unable to pass out my Python exam. Can someone help me out to easily remmember the lang??
probably, but not in this channel
is there any technical reason => lambdas can't be made available in Python?
like parser limitations
It should have been possible with the old parser
ye, the lexer can deal with the ambiguity there
Even the parser itself should have been able to parse that correctly
Well, you are correct (not sure why you deleted), but by a simple lookahead it should have been able to know if it is a tuple or a lambda
That's the "dangling else" problem described in the dragon book
because it could, which is why
(a, b)
(a, b) = b, a
``` are both possible despite `(a, b)` meaning different things in either case
Yup
so I guess it is possible
Meh, never had a huge need and python's design doesn't make the statements inside very nice
I dunno, although the current lambda syntax is very meh IMO
What's the problem with it?
I donβt know, it doesnβt really feel as natural as the rest of the language does
It is very scheme like, and that is not a great thing in a language that is not scheme.
I dunno, although the current lambda syntax is very meh IMO
@undone hare it is
and it's mildly irritating having "lambda" be a keyword
IMO the "lambda niceness hierarchy" goes like (a, b) => a + b > \a b -> a + b > lambda a, b: a + b > [](auto a, auto b){return a + b}
but I feel like neither of the first two would really fit in Python
The expression restriction is pretty big but I think it fits in with python's design
where do we use decorators?
@undone hare u read the dragon book? (The compiler one)
often, it is to transform the function into an object (@property @contextmanager)or to add it to some internal list (@typing.overload, flask route decorators)
huh
idk what those are lakamatiol i just started decorators
do u have a simpler answer?
ig no
To make the same change to multiple functions without duplicating code?
To be fair this is #internals-and-peps
well, sorry the description is not so clear i will just grab a help channel
@mint forge This channel is not for asking help question or help with learning how Python works. Instead, this is a discussion channel meant for people who are already comfortable with the language to discuss the language itself. That's why it's in the "Discusssion" category as well. The idea is that we have a lot of channels where asking for help is totally on topic and we want to have at least one channel where Python itself can be discussed, where people can have a conversation about that goes deeper into the language, and talk about the advanced concepts that are part of the language.
I think we already provide a lot of space in our community where you can ask for help with understanding and learning Python; this channel is specifically not meant for that.
ok
@undone hare u read the dragon book? (The compiler one)
@red solar yes, u am reading it
So I'm going to do some automation with headless selenium and am going to make a seperate environment for this
I currently run ubuntu on WSL with venv and anaconda just on my win10 base
Do you guys recommend setting up an environment in wsl? Is this easy to combine with stuff like vscode?
Alternatively, I can of course just create a conda env just in win10, but I heard setting up environments in wsl can be very helpful
for help get a help channel
@uneven oyster This is not a help channel, it's a discussion channel (see channel description). To get help, see #βο½how-to-get-help.
Oh sorry, in the help channel the question is usually gone in a few secs :C
@uneven oyster You should be able to claim your own help channel for your question, see the channel linked above. You will get an entire channel specifically for your question.
Oh wow I didn't know, thank you. I will have a look but right now fix error seems to help me in another channel already where's not many people π
There seems to be no available channels
Or I'm not looking good
Ah thanks!
np
solution=lambda n:all(k%i for i in range(2,int(k**.5)+1))if(k:=n**.5)==k//1<n else 0``` how can i make this code faster it returns True if the number has 3 factors and false if it has less than 3 factors
like the fastest code possible for this
i tried this
Let's say it even better. I have a 2D list where I want to append other arrays too.
[1] Array1, Array2
[2] Array1, Array2
......
[6] Array1, Array2
How could I do that without pre-defining the array size
Only define the max
[1]
[2]
.....
[6]
Append should immediately make you think of lists. Append is an insanely inefficient operation on arrays.
So one choice is to use a list first while appending and convert the entire thing to an array at the end.
Another as you mentioned is creating the entire array in one go and filling it up later.
solution=lambda n:all(k%i for i in range(2,int(k**.5)+1))if(k:=n**.5)==k//1<n else 0``` how can i make this code faster it returns True if the number has 3 factors and false if it has less than 3 factors
@gusty marsh probably not the right room for this, though I'm not sure where your question belongs.
#esoteric-python , most likely
hello has anyone installed pybullet for windows 10 here?
This is a discussion channel, not a help channel. See #βο½how-to-get-help
I'm busy now anyway so someone else will have to help
How are computers able to understand the length of a second? time.sleep is able to pause the program for around 1.00 every time, give or take.
There's a physical "clock" in your computer to keep track of time, then when you do time.sleep python tells the os you want the thread to sleep for that amount of time and then it's managed by the os' scheduler
The time is periodically synced with NTP to a time server too, which means it's in sync with an atomic clock somewhere.
I think this is an extremely bad example
Pandas would never do that
And what if you wanted to combine it with another logical mask
Nit picky but yeah, they should change that
yeah this feels like the one who wrote this example doesn't understand what it does
obj[spam=1, eggs=2]
# calls type(obj).__getitem__(obj, (), spam=1, eggs=2)```uhhhhhhh, why is that passing an empty tuple, i don't get why the semantics should be different from function calls
Because you need a positional arg there for backwards compat
can you provide an example where it breaks ? i don't see how that causes any issue given it's up to the type maintainer to allow for keyword arguments in {get,set,del}item
Actually, nvm.
here's a fun exercise:
In [91]: x = 3
...: x = maybe(None)
...: print(x)
...: x = maybe(100)
...: print(x)
3
100
None-aware function
it's pretty robust:
In [95]: x, y = 3, 4
...: x, y = maybe(None)
...: print(x, y)
3 4
In [96]: class Test:
...: x = 100
...: def reset(self):
...: self.x = maybe(None)
...:
In [97]: t = Test(); t.reset(); print(t.x)
100
i would trade ternaries for none-aware at this point
i want real sum types so bad
@prisma eagle https://gist.github.com/decorator-factory/b2fd85ef8248c9230835461c1ec24597
In [6]: class EitherStrInt(SumType):
...: Left.of(str)
...: Right.of(int)
...:
In [7]: e = EitherStrInt.Left("Error! Lorem ipsum dolor sit amet")
In [8]: e
Out[8]: 'Error! Lorem ipsum dolor sit amet'
In [9]: type(e)
Out[9]: embellished('EitherStrInt.Left', <class 'str'>)
In [10]: [isinstance(e, EitherStrInt),
...: isinstance(e, EitherStrInt.Left),
...: isinstance(e, EitherStrInt.Right),
...: isinstance(e, str)]
Out[10]: [True, True, False, True]
yeah, this is weird and needs some changes
not a fan of ADTs without a proper way to deconstruct them
yeah...
just like i'm not a fan of adding a way of deconstructing types without ADTs...
(go away match)
not a fan of ADTs without a proper way to deconstruct them
@teal yacht real programmers use.get()
i bet you're the kind of people that uses unwrap in rust
Well, we already have namedtuples and dataclasses, they can serve as ADTs. And the pattern matching PEP proposes a @sealed thingy that would make it better.
but, well, Python isn't statically typed, so many things will be weird
I really need to make better use of namedtuples. I've neglected them so
oh it does ? i guess i haven't looked at it in weeks now
i bet you're the kind of people that uses
unwrapin rust
@teal yacht whyflatmapwhen you canmapandflattenπ
ah yes >>=
ah yes
>>=
@grave jolt that's a syntax error by the way
you can't right shift into assignment
π
not in the correct language
haskel
!e
x = 64
x >>= 4
print(x)
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
4
emphasis on correct
STOP
I'M SORRY
hm
in-place operators can't return things, right
yup, they can't
oh well
@grave jolt namedtuple is a blight; it's pretty far away from real ADTs
had brief visions of turning __irightshift__ into bind
namedtuple is almost never the right answer
namedtuples have plenty of powerful uses
well, there's also NamedTuple
the thing i like best about namedtuple is that it gives us this mind-twisting definition: a tuple is a namedtuple without the names.
in-place operators can't return things, right
@gleaming rover wdym by inplace here ?
@full jay any that isn't handled better by attrs/datacalss?
@gleaming rover wdym by inplace here ?
@teal yacht__idunders
Sometimes you don't need that extra functionality you would get from a dataclass
Or you only need it in a few places
well, named tuples are probably faster with less implicit code
ah, yeah they can return stuff, and in fact they should
@prisma eagle much more efficient than dataclasses
@sacred yew "efficient"?
less mem
@teal yacht I suppose they meant that you can't do x = (y >>= z)
>>> class X:
... def __iadd__(self, other):
... return 3
...
>>> a = X()
>>> a += 1
>>> a
3
@sacred yew attrs with frozen=True; done
Ehh... less memory doesn't mean more efficient
also faster
i modified cluegen, so I could create classes with almost no boilerplate:
from .cluegen import Datum, CachedDatum
class Expr(Datum):
pass
class Op(Expr):
op, func
yes, several people have said "faster", and i don't believe it at all without an example
ascending past dataclasses
!e
do=lambda x:x
@do
def f():
x <- getLine
y <- getLine
putStrLn (show(x) ++ ", " ++ show(y))
# Valid python, can't complain
@grave jolt :warning: Your eval job has completed with return code 0.
[No output]
no stop aaa
Like I get what you're saying, @prisma eagle, but it's a matter of the right tool for the right job. Sometimes you don't need to or want to deal with making a dataclass. Sometimes you just need a convenient little thing. There is such a thing as class bloat
the attrs docs have a pretty good section on why namedtuple isn't worth using: https://www.attrs.org/en/stable/why.html#namedtuples
i don't remember when i was writing a new piece of code and actually added a namedtuple, however, it definitely has uses as a drop-in replacement for tuples to make the code clearer
So I should have to get a third party library for something that I can do natively? Or is that just listing an example. I get why you might not want to use it, but it's an odd hill to die on
@full jay Well, you can use dataclasses with frozen=True
But again, I don't always need all the extra bits and bobs you get with the dataclass
@teal yacht sure; that is the one use case that namedtuple is actually useful: backward compatibility in cases where you returned a tuple previously
that is what namedtuples were made for
@full jay i've used attrs longer than dataclass has existed; i don't think dataclass is very good or worth using. the points made in the docs aren't specific to attrs at all
It... it calls them "type clues"?
don't argue with beazley, accept it
@deft pagoda What black magic is this that calls them "type clues"
it's beazley, the antichrist of python
Seems like it
he's amazing
@full jay paradoxically, namedtuple gives you "extra bits and bobs" that aren't actually possible to turn off, like being iterable
attrs/dataclass lets you choose which parts you want
^
If you want a tuple with names, by all means: go for a
namedtuple.
the site put it well, I think
cluegen is great because it only creates code for methods when you call the methods --- otherwise it won't bother
lazy code gen
That feels dirty
it's sweet
But like... an intriguing dirty
i used to use namedtuple like this too before i started finding it exceptionally frustrating. all i want is classes without boilerplate, and i've started using classes more now with attrs because they're so much easier to write
i used to use
namedtuplelike this too before i started finding it exceptionally frustrating. all i want is classes without boilerplate, and i've started using classes more now with attrs because they're so much easier to write
@prisma eagle exact same experience
default values for attributes is the thing i'd consider the absolute bare minimum tbh, which namedtuple doesn't offer
@full jay ponder my class definitions here: https://github.com/salt-die/truth_tables/blob/master/truth_tables/expr_base.py
Salt, you are the master of the esoteric and the amazing
that is actually so cool
ngl, i don't see the difference with attrs/dataclasses in that example
wha... what are the characters in lines 39 and 41
@teal yacht what example
the same ones used in tree, I'd guess
the one salt-die posted
Ah, gotcha
as in cluegen vs dataclasses/attrs
class Op(Expr):
op, func```
other than making the code look weird it doesn't bring anything
yeah i disagree there, but to each their own :p
I believe that More implicit is more than implicit. the hidden kaon of python
i'm a strong believer that we should vanquish anything related to meta programming from almost every language, this kind of stuff gives me chill
boo to you
almost every language, lisp macros get a pass
uhh, well i'm a beazley fan-boy, i've watched his talks going back to, like, 96
Very cool
once you watch enough of them you start dreaming in metaclasses
@teal yacht what about rust's derive macros
Start huffing paint, got it
I can get behind hygienic macros in general i'd say, just the kind of stuff we see with exec/metaclasses in python is pretty eh imo
https://www.youtube.com/watch?v=E-1Y4kSsAFc 26:44 -- Async metaclasses
async def __init__ makes me frown extremely hard
really? because it dumps 3 days worth of dopamine in my brain
No pretty sure that's the paint
yeah, it's the same kind of fun as writing a Lisp interpreter in Brainfuck
use a classmethod if you want some async work, but that's exactly the epitome of the bad idea people are trying to discourage by saying "don't do work in __init__"
Brian Kernighan famously wrote:
Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?
infamously
I mean that's fair
the part i find enjoyable about programming is not making something """clever"""
I mean
you will have a heart attack if you look into #esoteric-python
That's the point he's making
good, keep to your side of the programming fence
Dude my head explodes when I look in #esoteric-python...
I just can't wrap my head around that stuff
I'm very inside the box
i wrote this once and then i got bored of the exercise https://paste.pound-python.org/show/chatserver/
Actually, namedtuples now allow docstrings, default values, extra methods and type information. Default values were a thing even before NamedTuple, interestingly. That's not to say that they don't have any issues like being iterable or not being as flexible as dataclasses.
!e
from __future__ import annotations
from typing import NamedTuple, Sequence, Union
class SExpr(NamedTuple):
expressions: Sequence[Expr]
class Name(NamedTuple):
value: str
class Int(NamedTuple):
value: int
class Definition(NamedTuple):
expr: Expr
lineno: int
docstring: str = "<term>"
def as_trace(self):
return f"({self.lineno}) {self.expr!r} : {self.docstring}"
Expr = Union[SExpr, Name, Int]
@grave jolt :warning: Your eval job has completed with return code 0.
[No output]
I don't think being iterable is a con
lmao
@deft pagoda Would you be comfortable if you were iterable?
C-can I iterate over you? 
it's not a con, having it always be iterable is, however
it's tuple, it should always be iterable
i don't think it makes sense for tuples to be iterable in general
.... why?
you what
I completely agree but eh
They're ordered
consider that they aren't iterable in, say, rust
why do we care about rust
What's the benefit of them NOT being iterable?
It's not just rust
why do we care about non-python language
It's basically every ML-based languages + type theory
that is, in fact, why i said "in general"
i don't think it makes sense for tuples to be iterable in general
@prisma eagle from a theoretical perspective, I agree
python uses tuples as immutable homogenous collections too
Well, in statically typed languages tuples have a more focused role; and they store heterogenous data, so it doesn't make sense for them to be iterable.
Different styles for different languages
i still don't understand why they shouldn't be iterable
Like, in Python *args is a tuple
are they not sequences in other languages?
no
@deft pagoda they are not
I hate it when the argument is "it shouldn't do it because this other language doesn't do it" or "it should have it because this other language has it"
so you can't index them?
It's irritating to me
but Python has this weird tuple which is kinda list-just-immutable and kinda actual-heterogenous-grouping
you can't, salt
then why do you want them
Well, in statically typed languages tuples have a more focused role; and they store heterogenous data, so it doesn't make sense for them to be iterable.
you can't, salt
@teal yacht how do you define "index"
tup[2] is not valid
@deft pagoda In statically typed languages they can't be iterable because... well, how do you iterate over a (str, int, bool) in C++ or Haskell?
You can "index" them (i.e. extract individual elements), of course
Position in the tuple?
@deft pagoda if we're talking about other languages this time, you can do let x = (1, 2); x.0 in rust to get the value 1 out
you can do it in C++ and Scala, at least
then it's a sequence
But we aren't discussing other languages, or should come back to the language this is about
@gleaming rover Well, in C++ you can do anything, but I assumed not using weak typing or reflection
oh, and the 0-uple and 1-uple should not exist either π
std::get?
@deft pagoda it's as much of a sequence as struct S { a: i32; b: i32; } is a sequence because a follows b lexicographically
0-tuple is the unit type, it makes sense if the language is expression-based
with an integer
@deft pagoda so, you agree: not really a sequence
if you can do S.0 and S.1 yes
Why would you be able to do that π
I don't think so...?
@deft pagoda the x.0 in rust is a literal 0; it doesn't accept an int as an argument
? 0 is an int
Cool, glad this Python server is getting derailed
sequences and indexables don't necessarily overlap
maybe let's move this discussion to #ot-*
Yes
all i've gotten from thisi s that tuples should be iterable
@full jay consider that it's beneficial to talk about other languages in reference to python because you can learn from prior art. that certainly would've made the typing module less of a horrendous mess if they consulted prior art..
this isn't offtopic --- if it's a discussion about whether some type should or shouldn't have an __iter__
if the central discussion is tuple, fair enough, I would say...?
Yeah sure fine
and honestly why doesn't it make sense to map a function over a tuple, as long as the function takes a common subtype of the tuple's elements?
e.g. str or the equivalent
what do types matter
because they help proving (to an extent) your program works
it's all PyObj
because they help proving (to an extent) your program works
@teal yacht in this case it wouldn't break type safety, right
that "to an extent" varies more or less with the type system used
oh
the idea behind tuples is that they can store heterogeneous elements
that's one idea behind tuples
if you're iterating on a tuple, how would you know what type you're getting
if you're iterating on a tuple, how would you know what type you're getting
@teal yacht common subtype
it's not the idea
In programming languages and type theory, a product of types is another, compounded, type in a structure. The "operands" of the product are types, and the structure of a product type is determined by the fixed order of the operands in the product. An instance of a product ty...
Wouldn't that only apply if you're getting outside input?
it's not the idea
@deft pagoda based on the theoretical origin (which need not be authoritative), it is
I mean if you're programming it, you have direct control of what the types are, where they are, etc.
In mathematics, a tuple is a finite ordered list (sequence) of elements. An n-tuple is a sequence (or ordered list) of n elements, where n is a non-negative integer. There is only one 0-tuple, referred to as the empty tuple. An n-tuple is defined inductively using the constru...
tuples relate to product types in much the same way ints relate to mathematical integers IMO
this says nothing about the elements being the same type
for context, I'm a mathematician
But does say that it's an ordered list/sequence
so, this is where my intuition of tuples comes from, not from comp sci
that article is wrong then, it lists the fact that it's a sequence as a property, then proceeds to say "Most typed functional programming languages implement tuples directly as product types,[1]"
algebraic data types don't come from "comp sci"
well, fill free to edit the article
or it as much comes from "comp sci" as from "math"
Pretty sure it was a math thing before comp sci
quattuorvigintuple
thanks now I will use this
Not to say it can't be appropriated for another purpose
virgintuple? π€
VirginTuple new type coming soon
I think the only other argument I have about the whole tuple thing is that it's not consistent between languages. It's different for some than others
Doesn't make one wrong or right, just specific to that language or that paradigm
well
It's why I'm scratching my head as to why there was even this argument in the first place
just like all normal people arguments end with mentioning nazis, all programming discussions end at "it depends"
another reason python is attractive to data scientists
tuples are mathematical, and list comprehensions are set-builder
Oh huh.... hadn't thought about the latter
quick question
i work with data scientists that don't come from CS backgrounds, and they couldn't care less about tuples being "mathematical"
is it true that for all classes X without __setattr__ overloaded, object.__setattr__ is X.__setattr__ ?
the only reason python is so prevalent in DS is that it's easy to pick up and the snowballing effect the community has started
that's great, let them write their piece, because "I know people" too
@teal yacht Is that a bad thing or...
why do you have to be so condescendent in every of your messages
Me?
no, @deft pagoda, "you're wrong, i'm a mathematician"
I think the only other argument I have about the whole tuple thing is that it's not consistent between languages. It's different for some than others
@full jay I guess the thing is
some languages are designed with a greater focus on specific theories and paradigms
and some others...spring up.
and sometimes they reinvent the wheel
not really a problem
but I can see why it could confuse others
Sure, fair enough
e.g. Haskell's class is quite different from what we see in most "traditional OOP" languages
and no, it's def not a bad thing, python is popular for many reasons, the ecosystem being a large one is the main reason why i use it too, i'm just stating that it being popular because "it uses set builder notation" is a large stretch
haskell also has list comprehensions, and it's not popular in data science
even though Haskell is older than I am
I wonder if it's older than me..
1990
haskell not especially readable besides the comps
Nope, same year then
is Haskell even readable?
Not to me
Haskell is not even writable π jk
foldr
foldr1
foldr1'
no, because people are not used to it
it's why I sometimes wonder if Python would be better if it allowed custom operators
like Scala does
but I feel that would make it weird
more dunders?
and we would have Python foldr1'
More than it lets you over- ah okay I see what you mean
Doesn't quite feel intuitive or readable, though
yeah, that's how Scala does it
reasonable
but then you would need an "all functions not starting with an alphabetical character are called with infix notation"
rule
...or just + 2 3 π
map (+ 1)
is it true that for all classes X without
__setattr__overloaded,object.__setattr__ is X.__setattr__?
@gleaming rover so I'm p sure this is the case, but I'd just like confirmation
!e
class A:
pass
print(A.__setattr__)
@grave jolt :white_check_mark: Your eval job has completed with return code 0.
<slot wrapper '__setattr__' of 'object' objects>
ye
Okay, quick thing. That face doesn't look woozy. Looks more like someone who just saw the person they have a crush on
Nah it still looks woozy for me
same thing
just looks like a fancy mustache
@full jay isn't that woozy still
I suppose so
Scala letβs u have functions with non alphanumerical names?
I think I was just expecting one of the eyes to be slightly closed or something
yes, operators @red solar
Whatβs the limit on what characters are allowed in an operator name?
no idea
I am not sure if u call this advance or not but how can I use os to rename a file but rename the oldest date modified file will be first
@plucky scarab This is not a help channel, this is a channel for discussing Python itself (read the channel description). See #βο½how-to-get-help if you want to get help.
Sry
hello
@half drum
This has to do with how classes are constructed.
class A:
def f(self):
return A
this is fine ^ because A will only get accessed after the class has been created.
In Python, function definitions
def f():
...
and class definitions
class A:
...
are very similar to variable assignment, like f = something or A = something.
So constructing a class like
class A:
def f(self):
return (42, A)
x = 5
is pretty much the same as
A = type("A", (), {"f": (lambda self: (42, A)), "x": 5})
To create a class, you need to supply:
- its name
- its parent class(es)
- its "dict" -- the values to assign to a class, like
fandxhere.
So when you do
class A:
the_instance = A()
x = 5
you're essentially doing
A = type("A", (), {"the_instance": A(), "x": 5})
...and this will not work because this needs A to exist before it's created (just like x = 5 + x doesn't work unless x had some value before)
Thanks a lot man, trying to understand
If you don't understand some of that, feel free to ask, or maybe claim a help channel
Okay. Thanks! I will do that after i try
@grave jolt What are you doing with type() here ? isn't type(object) used to find what class the object is made from ?
type is overloaded, kind of...
let's move to a help channel, I guess
Hello, I'm trying to pack elements of a numpy array two by two in tuples : python print(array) array = pack2By2(array) print(array)
would give ```
[ 1, 2, 3, 4, 5, 6, 7]
[ (1,2), (3,4), (4,6), (7,nan)]
or
[ (1,2), (3,4), (4,6), 7]
I could implement the function pack2By2 but maybe it already exists?
that seems somewhat similar to reshape
Please anyone can suggest me on this problem:
Problem Satatment: You are the metro corporation and you can take any steps or implement any technology in the world instantly. Today is a Tuesday and day after tomorrow ie. Thursday morning, you want to know the total number of distict passengers that traveled in the metro on wednesday. How would you go about solving this problem???
@oak fiber try #βο½how-to-get-help
Hello, I'm trying to pack elements of a numpy array two by two in tuples :
python print(array) array = pack2By2(array) print(array)
would give ```
[ 1, 2, 3, 4, 5, 6, 7]
[ (1,2), (3,4), (4,6), (7,nan)]
or
[ (1,2), (3,4), (4,6), 7]I could implement the function pack2By2 but maybe it already exists?
@lunar panther try #data-science-and-ml, I think
this might be a dumb question, but why don't someone take something as powerful as c++ and make it easy to use like python
because it is not really possible. Power comes at the cost of complexity
aw
Python and C++ both are high level language right?\
idk
@mint forge right
If only python wasnt dynamically typed
@compact horizon (response to dm) in a dynamically typed language you don't have to specify the type of variable
Is Python's speed actually the result of it being dynamically typed, or is it because of the interpreter architecture itself in general?
Both
@jagged tree look up nim and swift for example.
Python isn't really simple, it's just that simple things are simple. You can do this in a fast language.
Calling C++ "powerful" isn't very fair I think. Python is more powerful. C++ is just fast at runtime mostly, but it's less powerful in what it can express, slower to compile and slower to develop.
Lisps are more powerful in what they can express but quickly become confusing and messy.
Pretty good summary of when to pick certain languages over another
pretty much every modern programming language is turing complete so imo there is no point about talking which language is "more powerful"
pretty much every modern programming language is turing complete so imo there is no point about talking which language is "more powerful"
@unkempt rock I think when people say "powerful" they generally mean "capable of expressing complex abstractions in the problem domain with ease"
Is Python's speed actually the result of it being dynamically typed, or is it because of the interpreter architecture itself in general?
@brave badger the latter is because of the former, so both
its also the fact the language lets you access very low level parts of the interpreter
I may have worded it a bit incorrectly but what I meant was basically the fact that there's a bunch of articles talking about how Python is slow solely because of dynamic typing without actually going into the specifics of the CPython implementation, which I hate
a great counterexample is something like CL and scheme
That's what I'm thinking as well
@unkempt rock well obviously no. We can compete in say writing a csv parser. I get to use python (but not the csv module from the standard library obviously) and you get to use brainfuck.
Both turing complete so it's a fair fight!
@brave badger agreed. But a lot of the problems pypy have in making it go fast is due to the dynamic features afaik.
afaik, the issue is more keeping compatible with cpython impl details and the fact everything must be an object for is to work correctly
I mean, dynamic does not help, but there is a reason pypy is slower than V8
The big reason is the amount of time and energy put into it.
Pypy has lots of problems with cpython extension modules yes. But that doesn't explain why pypy is sometimes not much faster when it's all native python.
Javascript is fast because there are enormous amounts of R&D poured into it. Pypy is two guys with almost no funding.
One of the softwares that we work with, cancels Python support in favour for C++ and LUA... (Personally hates LUA), reasons ... Python is slow...
It's called Lua, not LUA. It's the Portuguese word for moon, not an acronym. @coarse tundra
I maintain a rather large OSS project written in Lua and I think the language is mostly fine, even though I would prefer it to be written in Python
Interestingly, the most popular third-party library for Lua, Penlight, aims to bring many Python idioms over to Lua
So I think many developers who don't code in Python also appreciate its language features to some degree when they encounter them in other languages
thanks for sharing that knowledge, i didnt know
Python has too many caveats to be worth it imo. Anybody who has worked with a huge enterprise codebase in python knows how it's hell to deal with
Dynamic typing was cool 20 years ago, now it definitely shows its flaws
true
I'm personally in data, and I use python cause I have to, but at home I prefer julia 100x. Python at least is not too bad as a glue language, but even for that
where do u learn from?
what do you mean?
i mean like python where do u learn
I learned by myself. Had a lot of prior knowledge in C++ beforehand
oh ok u seem to be an advanced programmer
afaik, the issue is more keeping compatible with cpython impl details and the fact everything must be an object for is to work correctly
@flat gazelle everything being an object isn't an implementation detail, though, it's a fundamental language design decision
thats why the and is there
Ah, two separate points. Ok, fair enough. The "implementation details" part is I think not particularly true when it comes to running Python code in pypy, but it definitely comes up for making CPython extension modules run in pypy
@lean garnet have you tried using type hints and mypy?
@lean garnet i'm also curious what caveats you mean (other than dynamic typing)
Dynamic typing was cool 20 years ago, now it definitely shows its flaws
@lean garnet thereβs no perfect language either
I disagree with people saying Python is slow given its flexibility
Anybody who has worked with a huge enterprise codebase in python knows how it's hell to deal with
@lean garnet
Disagree. I work on a 280kloc code base. Have been for 9 years.
even in Google thereβre tons of stuff written in Python
"everyone knows X" is hardly a convincing argument π
What IS hell is shipping code. And C++ ;)
I hope google doesn't mix camelCase and snake_case in their production code like they do in their API wrappers π
they use two-space indents, there's no talking to them
They're using 4 in the wrapper π€
Their documentation hurts to work with
You have to go through a maze of links to get a general idea of how to do something
I have the same experience, but thankfully I didn't need too much integration.
only google? its more like a common practice in the industry
Id say its rare to find superb documentation
At one point I tried to make an attachment extractor so I could pull all the various junk from my email. I've had the thing since high school, so it was a bit of a mess. I spent days on it, and I still couldn't get it to work exactly right.
@viscid lintel A good portion of the specifically Python documentation is very clean, actually
Various libraries, integrations, etc.
well they had Guido and the first crawler was written in .py iirc
Sure, but I'm not just talking about the official docs
There's been hundreds if not thousands of docs since
i"m trying some kickstart prob. using pyhton and I need help I'm facaing some error.
most of time my code rejected due to some Runtime error.(shown by kickstart)
its working fine in terminal and other editors but on submitting it on kickstart my codes show runtime error most of time.
@unkempt rock Unfortunately this channel isn't really meant as a help channel. You'll likely have better luck using our help system. See #βο½how-to-get-help for more details
indeed improving documentation is a good way to contribute and maybe get a free tshirt in hacktoberfest
"fix typo in docs" is my favourite commit type
I mean it's a good and important part of a language's ecosystem in general, t-shirt or not
I think a lot of other languages could use some TLC in their docs as well as with any libraries associated with them
Python's just lucky because the idea of clarity and readability is ingrained in the folks who love it, and that trickles down even to their docs
Doc fixes are also a great way to learn how the project manages contributions, which will make things much less difficult if you want to contribute something more involved later
Is there an annotation to indicate that a class method should return a subclass instance of that class?
Might have to be in quotes -> "ThisClass"
At least until postponed evaluation is a thing
If the return value could also be an instance of a subclass of ThisClass, I believe it'd be -> Type["ThisClass"]

Type will mean it expects the actual class object to be passed in, not an instance iirc. Just ThisClass should also include all subclass instances
Wait so
To clarify, it's what nedbat mentioned earlier, just wrapped in quotes
you don't need quotes if you use a new enough python, or a from __future__ import annotations import
That won't be the default until 3.10, AFAIK
Good to know
Inheriting from class foo(abc.ABC,meta=CustomMeta) allowed or bollocks?
Is there an annotation to indicate that a class method should return a subclass instance of that class?
class Parent:
@classmethod
def make(cls) -> Parent:
return cls()
^ this means that for any subclass Child of Parent, make will return an instance of Parent, not necessarily an instance of Child, which is probably not what you want.
This is how to fix it:
P = TypeVar("P", bound="Parent")
class Parent:
@classmethod
def make(cls: Type[P]) -> P:
return cls()
Now Child.make() is identified as Child, not Parent.
@swift imp ^
Ty
do you think there will ever be another way to specify type parameters
this TypeVar thing is honestly so ugly
and verbose
Initializing a subclass instance during __init_subclass__ is that possible given the mro or no?
@gleaming rover Well, one way would be to just use strings, I suppose.
generics when
Can't you already make generics though?
I remember seeing something similar
You can indeed do generics with TypeVar
@cloud crypt when would you use that?
what does nifty mean in this context
Sounds like one of those things that's above my head. Also sounds quite powerful
Interesting, I'll give that a read later
Am I correct in understanding that it's essentially designing a mechanism for code substitution before compilation? Not so much so as a concrete use case, rather a feature that enables people to create their use cases from code substitution?
i mean you can achieve code generation using exec which is what most if not all code generators use todo so
what most Python 2 and Python 3 compatible packages do to dynamically change depending on the python version
i have no idea what it's about still but if anyone has a basic example of what a macro is in this context and why/when it's useful that'd be appreciated
tl;dr macros basically generate code before runtime. They're especially useful for abstracting routines with little to no runtime cost afaik.
what are opinions on assert statements? I've only just read (https://stackoverflow.com/a/9626854/3130747) that they get removed at some point, so are they just meant to be a temporary helper for the developer rather than ensuring the proper types are passed to functions? Bc sometimes I'll have ~4 assert statements at the top of a function, which makes me feel as though I'm doing something wrong now
Do you need those asserts? They're intended for tests etc.
It's for usage though - I know it'll break, but wanted a useful message if the wrong value is passed
If they were all moved to unittests, then I could run pytest or whatever and make things ok, but someone could still pass in an array which will fail with the function. Maybe people just let things fail the way they fail? Seems less helpful than giving a particular message for the problem though
you can always raise custom exceptions
so instead of 4 asserts in a function you'd have 4 raise ValueError( ... ) or similar?
yes
that makes sense
Validating inputs if it helps wouldn't be a bad use case, but feels like it would make the code a lot more noisy. The expected arguments should be documented and if the user passes something that doesn't use that, that's their problem. The assert mainly shouldn't change the logic of the code since they will be excluded in compilation with optimize flags
The expected arguments should be documented and if the user passes something that doesn't use that, that's their problem
Yeah, that also makes sense. Hrm, they do feel messy
I'd say that's not a hard rule
raising custom exceptions would be even messier i guess, if not condition: raise <exception>
For instance if a function takes in a data object but the function requires that the element x be a specific value if element y is a specific value a custom validation exception fits
That type of pattern is used a lot in web apis
i have some things checking that the dimensions are correct, eg matrix has >2 columns and stuff. So, that could be put in the documentation, or it could be done with assert <all rows have same number of elements>, "blah", and it's not clear to me that the latter is worse than the former
@magic python asserts are removed if you use -o yes which is weird and no one uses it. Asserts to check invariants is perfectly fine imo. I use it all the time.
fair - just checked out numpy does some of it - they use stuff like :
def _assert_2d(*arrays):
for a in arrays:
if a.ndim != 2:
raise LinAlgError('%d-dimensional array given. Array must be '
'two-dimensional' % a.ndim)
As long as the error message is very good I don't think the type is very important. Unless you do want to handle it obviously. All problems that are for dev time can be asserts.
yeah, and in pandas they have
def _get_grouper_for_level(self, mapper, level=None):
assert level is None or level == 0
etc... hrm, I guess it's just subjective - I don't think I like having them in the documentation as much as the code
docs are easier to rot for me at least
Yea. Executable > not executable.
@cloud crypt seems subjective, and I haven't really seen a clear example of why it isn't having searched a bit. Other than it being dropped when running -o at least
The type also isn't very descriptive
i fail to see how something like
def check_dim(A):
if A.shape[1] < 2:
raise ValueError("Array requires at least two columns")
is much better than
assert A.shape[1] >= 2, "Array requires at least two columns"
I'm probably missing something
eh
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 can help to perform this ?
if you want to load a custom module, you don't have to save any files to disk then load them
because you can load a module directly from the code in memory
not from a file path like with import or __import__
@cloud crypt asserts are much better if it's mostly for errors done while developing. That goes very much for libs.
Raising a specific exception can be worse because it can be caught incorrectly too.
I've worked on a project where developers used asserts a lot as sanity checks that eventually made it into "production" (maybe not a good word because the product was transformed data, not the code itself), I don't have any strong feelings about it as long as everyone is aware that -O will ignore them
At the same time I'm not aware of -O even being used anywhere, but maybe that's my ignorance
Yea, -o should be removed. If you want faster python, write an extension, don't just delete asserts.
@cloud crypt sure eh but you've not actually given anything concrete, just preference, hence me assuming that's all it is, preference
Yea, -o should be removed. If you want faster python, write an extension, don't just delete asserts.
@half wolf it also sets__debug__toFalse
I don't actually use it but I can kinda see the use case
AssertionError has those test vibes
I use -OO regularly when distributing apps, It's not exactly python's best use case but the flag does help with it
Yea it's like "optimize!" and then it doesn't really.
@gleaming rover hmmm... Yea well. For example django has settings.DEBUG instead because that thing isn't useable as we've established.
For envinonment management in WSL, venv or conda, what do you recommend?
I like pyenv with pipenv, works great for me
None of the above, just docker.
pipenv builds on top of virtualenv
conda is probably good on windows, some of my coworkers like it
Speaking of environment I always use pipenv and virtualenv (venv)
I'm not sure if beautifulsoup would be advanced? Can someone help advise if I should be posting my question about beautifulsoup here or in the general channel?
If you're looking for help, either a help channel or perhaps #web-development if you feel like it's appropriate would be better places
This is more for discussion
Perfect. Thanks @sacred tinsel
no worries
I'm using it in my python program. Does that change things?
no, that just means you're in the right server
Word.
I need a help
A array is given consisting of A ones and B zeroes
We have to select C elements from array, delete them from array and append their average in fraction form to the array
At last only one item remains in the array
Input:
A:1
B:1
C:2
Output: 1
The array is [0, 1] I have to take 0 and 1 and delete them and add 1/2 to the array
Input:
A:2
B:2
C:2
Output: 5
There will be 5 possible values 1/4 , 1/2, 3/8, 5/8, 3/4 and at last only 3/8 will left
Delete 0 and 1 and append 1/2 to the array
Delete 1/2 and 1 and append 3/4 to the array
Delete 0 and 3/4 and append 3/8 to the array
Please help me
this isn't a help channel, check out #βο½how-to-get-help @fiery cradle
anyone know how to write the function total gpe in a 2d system for πππ=-πΊππππ/πππ, where user inputs the number of grid-points in a system where they are spaced 1 meter from their neighbor?
this is not a help channel
ahh, my b
wouldnt it be way more memory efficient for python to draw methods from the class itself instead of giving every object their own individual copies of each method?
Methods are looked up at the class objects from the MRO, they're not attributes on the instance object
Anyone have advice on a pattern where the parent captures an instance of the child upon definition? I was going to do this in __init_subclass__ but realized its way too early, and not possible because still have to go through __new__
No instance exists at definition
Ok, maybe after definition?
I realize I cannot do it during __init_subclass__ but can I do it in another dunder?
If you want to log instances at creation, put a weak ref into a list in __init__


