#python-discussion
1 messages · Page 333 of 1
@raw bramble right now I'm doing 3D in Python, and almost all the really heavy work happens on the GPU. It's just a matter of getting it into the GPU in an efficient way
the not-from-scratch way is to use pydantic or msgspec
I find understanding low level concepts in any field helps grant me a greater understanding of the higher-level concepts, but it's not neccesary for me to work with them
Computers are essentially just bunch of 0 and 1 manipulated in different ways
remember folks, whenever you thinking learning low level is the only way to make money, remember that bill gates wrote DONKEY.BAS.
having some basic idea of the systems you work with is a good idea, sure (and most people will probably have more than that--most CS programs will have you take multiple courses about systems and computer architecture).
Although for me it's a bit more extreme than most people. I can only really feel concrete in my understanding if I know the ultimate Why and How to something
9.0%4
Out[22]: 1.0
-9.0%4
Out[23]: 3.0
how ?
can anyone tell what's the logic behind this
Like under the hood insertion in a list is O(n) but unless you're using 10²⁰ length of lists you'll never feel the O(n)
.
I tested this you just have to insert at the front in a for loop so it becomes 1 + 2 + 3.. n = O(n²) then it becomes painfully obvious
Like with addition and multiplication. Although I've understood them since I was a child, I feel like I understand them more now that I understand their commutative and associative properties
The strategy is building your own wheel 💪
But I've never needed to know or understand those properties to do maths
Yes
im very aware of the strategy.
https://Nandgame.com is a very fun website ngl.
but i dont ahve time to do all that, its a poor choice of tool for the job in hand
I love doing this so much
If I can create that thing, then I should be allowed to use it.
If I can't yet, and I don't need it, then I shouldn't use it
The official syllabus for computer stuff is so bad the last thing I remember studying in my school is www and html with styling 💀
im looking for an expert of python for a new project. If u r one, plz send me a dm.
css?
9 is 4*2 + 1, and -9 is 4*-3 + 3, so the remainders are 1 and 3 respectively
Html is kinda easy
Idk web development seems boring
You can always just message in here, there's plenty of people who know python and will be willing to talk to you in one of these channels, less so in DMs, though.
They're still teaching html with styling in schools , outdated syllabus
Css was never taught to me.
okey sorry
my school taught html and visual basic, but the teachers didn't have the best grasp on much else
so someone can help for a project plz
what's your project, you can always just as your question
no need to ask to ask :P
visual basic . net? or the old visual basic?
old.
i was devestated when it went to DOT NET. even the name is awful. DOT NET.
vb6 captain here all the way!!! boarn and BREAD!
I can't remember 😭 it really could have been either
used to get bullied for it. but now it's 'retro' people are starting to say its actually somewhat 'cool.
I'm going to guess .NET, but that's entirely a guess based on vibes, it is equally as likely have been VB6
You shouldn't be bullied for using VB6. ||you should be bullied for using Visual Basic 😭 ||
give it your best shot. only rule, its face to face and not behind a screen.
I can't be mean to people in real life, I don't have a real life 😢
i figured
aw man
also you do realise we are in a python room. lol
its not exactly sega megadrive assembly
roasted mode
Visual Basic itself is a bit outdated nowadays
visual basic 6 did me well.
as i said yesterday, i just cant continue with windows.
Dnam how long has been? that is like 2000 era
visual basic's biggest flaw being, windows
Same, I swapped to arch last week, I have no clue what I'm doing for some things because the tutorials aren't specific enough, but I'll figure it out some day
i'd strip it down to a black screen write terminals, do opengl graphics and stuff, make it procedural. lots of fun and learning
oh and also i got it free, i think its OK to confess.. it was stolen many years ago
I need to figure out what my "workflow" or my "style" is for working with my computer, since with Windows I never had to think about it, I was forced to do what Microslop wanted
You went windows-> arch?
Yeah
I've had experience with Linux before, just not on my home computer
Ah good
I always thought it'd be so hard to find all the files I want to keep and back them up, since file management has always overwhelmed me, so I never swapped before
I'm loving Hyprland though :D
opengl graphics in terminals
no, comma, new item: do opengl graphics and stuff.
pygame is debatable though, aye?
but but
Lowkey Hyprland is the best wm I ever used
opengl graphics in terminals
ah okay
Now make it interactive with touch monitors
it is interactive, you can click on it and make a new thingy appear, i think it shows in the video
I've heard that Vulcan is better for modern, high-end devices?
How much more complicated is it than OpenGL?
from dataclasses import dataclass, asdict
import json
from pathlib import Path
file_path = Path("./jsoning/files.json")
@dataclass
class Person:
name:str
def open():
with file_path.open("r") as f:
print("File loaded succesfully")
return json.load(f)
def save(data):
with file_path.open("w") as f:
print("File saved succesfully")
json.dump(data,f,indent=4)
test = Person("Jane")
data = open()
print(data)
save(data)
In order to update some json file, I'd need to convert all of the entries in it into instances of a dataclass inside a list, right?
Then do add more people, I'd need to add more instances of that dataclass to that list
Then to update the json file, I'd need to convert the list of dataclasses back into json, then save it?
If the question is "how do I update a .json file" then yes. You need to read it, make the changes, and then write it back out.
I'm trying to make a small CLI tool that lets you make a task-list, and check them off once they're completed. I need a way to save the tasks, so I thought I could use a json file for it
A json file is one way to store structured data. Sounds like a plan.
How do I convert the json string into the dataclasses?
You don't have a string. json.load(f) retruns a dictionary.
Well... it returns Any.
But you either have a list of dicts or a dict. Print it and look.
this is my temp json file (i needed something in it so the code would read something)
[
{
"name": "John"
}
]
Yeah it returns a list
A list with a dict in it
So you'd need to iterate through the list and then create an instance of your Person dataclass for each item.
you can do __as_dict__ in a dataclass, right? is there a way to make a __from_dict__
Hey @pure grotto!
Add a py after the three backticks.
```py
print('Hello, world!')
```
This will result in the following:
print('Hello, world!')```
You can write your own. You can also splat the dictionary you have into the dataclass. Although this requires the file to always match the dataclass. new_person = Persion(**my_dict)
splat?
(Dont use dataclasses_json, which is overly complicated and unmaintained for a few years)
I've tried looking this up and it told me to use that, which I took one look at and decided it's too complicated
but also damn, google, and all search engines have gotten way worse recently
Yah, look at git issues . Its abandoned
I remember when I first joined here, I asked questions because I couldn't understand the answers given by search engines and needed someone to explain things in a human way (I still find conversations a much better way of understanding and learning), but now I'm asking questions here because I get no good results now when I search things up😭
I have to ask things here now, once again
Is there a reason your mixing making a new app with dataclasses? It seems your new to both json and dataclass. Could be easier to just work with json and then add dataclass later.
unfortunately, I'm not new to these things. I've just forgotten that much about python D:
I wish I was just new to these things, but most of the time when I'm asking a specific question here, it's because I used to know that thing :(
You do you, there is no judgement here. Just suggesting breaking off a smaller piece.
I hate when searching for docs of something in Python and the results are Geeks4Geeks and RealPython
realpython slander
How would you work with json and non-data classes
Shitpython
realpython isn't good, it's just better than Geeks4Geeks.
Imagine needing to login in a website to see basic things of Python
Delete your cookies after every couple of pages you open
That the official docs do it for free
yeah the login banner is terrible. but I think it won't show up if you use incognito mode
I think a website that explains python concepts like actual humans having a conversation or actually learning about those concepts and answering questions as they'd naturally come up would be good
Official python docs solos every other tutorial
I mostly use RP as a friendlier alternative to the docs specifically for beginners for whom the docs would not be enough of a "tutorial" kind of resource
tutorial.py needs to exist
Just work with the data as a list and dict in the code. How familiar are you with that?
not the most familiar, from the moment I learned about dataclasses i've used them
Is anyone of you here familiar with whatsapp api??
Do you want to stick with dataclasses? You're driving here.
I think I'd like to use dataclasses, since I've always used them. I'm guessing without using them, I'd make a function that checks the keys of a dict to make sure they match up to my target (making sure this isnt some random dict), and then changing or adding values.
I think it would be valuable to get some experience in working with just lists and dicts
forget this
Ah peer pressure.
My biggest issue has always been knowing enough about things to move on without fully understanding them
If you let Pydis drive, you'll be loading pydantic base models for your very starter cli app.
((this is humor))
In terms of Diataxis, the official docs cover the "reference" and "how-to guides" quadrants very well, and sometimes touch on "explanation". But there's not a lot of "tutorial" style materials, especially for people relatively new to programming.
For example, this is all the official tutorial has to say about generators: https://docs.python.org/3/tutorial/classes.html#generators. I think it's pretty difficult to grok generators from such a short description and literally just one example
if I have a file like this
{
"first_name":"John",
"last_name":"Jane",
}
and use this
with open("./jsoning/people.pydict","r") as f:
data = f.read()
print(data)
that retrieves the dict as a string
use json.load
You can't have that though. A dict cannot have duplicate keys.
Yup, the edited will read the file as a string. That's where json.load() or json.loads() comes in.
Person(**your_dict) will make an instance of Person assuming the dict has all the attributes
what's the difference between .load() and .loads() ?
.load takes a file object, .loads takes a string
Indeed. Btw i was joking.
I asked the same thing a while ago too for dump/dumps And the "s" in loads stands for string from what i recall
Yeah. I was like you, scratching my head about what it could be.... Then asked here, people replied and then oh that makes sense!!!
foo = json.load(open("foo.json", "r")) so convenient
sup
@robust ledge like this?
import json
with open("./jsoning/people.json","r") as f:
data:list = []
try:
data = json.load(f)
except json.decoder.JSONDecodeError:
pass
def add_data(first_name:str,last_name:str):
new_dict = {
"first_name":first_name,
"last_name":last_name
}
data.append(new_dict)
print(data)
add_data("john","doe")
with open("./jsoning/people.json","w") as f:
json.dump(data,f,indent=4)
Does it work?
yes :D
Great start then!
I can create new data, but I'm thinking about editing existing data, and deleting data now.
You are mutating data as a global object though and that will limit or complicate what you can do later. Maybe return the new dict from add_data and append it outside of the function.
e.g: Instead of add_data() maybe create_person() and move the append out of the function.
alright :P
or carry on and figure out editing. :P You're driving.
del
hello
can anyone remind me how to make it so that the printed text can go down a line like
this
\n maybe?
Oh ye that thxz
You'll never forget that in Cpp
🤣
noo clue what that means
Blud doesnt know 💀
they are bragging about their knowledge of how to print hello world in C++
ah
Honestly couldn't care ik i never learning that stuff
You are going to
Everyone is capable of learning
You should at least know some
Yeah 1200 rating in Codeforces by printing hello World , it is really disrespectful to say someone else is bragging when you don't know them
Guys i code on google collab…. Can u guys tell me till where it will be good there cause since it’s free so and i have to spend money for a laptop … i got an ipad rn
Google collab?
Yeah
An used lenovo thinkpad is probably fine
Yeah google colab
Whenever im on my phone i usually just use notepad
I have two if statements that include the same condition, better that way? or have them nested in an if statement of that shared conditon?
speed wise
im having speed/throttling issues
I got a keyboard attached to ipad so its just missing the software at this point
I found your comment to be equally disrespectful. I read it as “look, I know C++, i’m smarter than you”
Send a snippet of your code please
For sure
Dunno but a single line text is often faster
I'll try not to be like that next time , I really didn't mean it :(
no worries
What's the minimum effort to make an object class DefaultFalse which is falsey and can be used in bool contexts? E.g. debug: bool = DefaultFalse()
How do i attach it? i normally upload the file in the forum but i cant in the chat
!paste
So that everyone can easily read your code, you can paste it in this website:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Use https://bpa.st/
ik, im just not sure how to upload it to the chat. i cant upload a file, i usally download it from the website
you can send a link to a pastebin
Post your code on https://bpa.st/, and then share the link to it here
Ok so your code has 1 equal statement
self.mouse_position % 25 == 0
You could make an inverse statement that just ends the function early like this:
self.mouse_position % 25 != 0:
return
oooo whats that?
click the link to answer your question
i not relize that was a link 🤦♂️ 😭
Okay il test that
i assume you meant to have an if at the start of that?
Then you could do this
if self.mouse_position > self.rect_counter:
...
else:
...
Or the logic of your code has a case for mouse_position being equal to rect_counter?
not something i need to worry about
Ok
Can yall give me some begginer python projects that will make me come back the next
Day to make upgrades or smthn
Hmm, still having some delay issues
What is this project?
downloads folder sorter.
in lamens terms. a glorified calendar app. This rect is the events that the user adds to their calendar. and this feature i linked is what allows the user to expand the event/task/appointment etc to when it ends (like any other calendar app). so the delay happens when i try to expand it fast.
Recreate grep
i linked*
Maybe its doing alot of drawing?
https://bpa.st/43AQ i think its just "self.setRect(rect.x(), rect.y(), 223, rect.height() - 25)" thats doing any "drawing" feel free to look over the code if i missed something else that does.
Are you pulling the events off a queue or a stack
Im sorry, i dont know what that means
.
Idk I remember this being a problem where the events were poped off and the order was reversed so it didnt resize correctly
Okay....
alright
How am I meant to install python on arch?
I used yay for it, but I just realised I don't have pip, and I kinda want to be able to just run .py's without having to say "python" at the start of them
pacman -S python
Run with sudo ofc
Oh you want to run without calling python
Wouldn't you have python already installed?
You might find pip is an additional package - it is on Ubuntu.
If you want your scripts to be commands:
- make a directory for your personal commands (I use
~/bin) - put your script in there without the
.pyextension - make it readable and executable by you:
chmod +rx your_script_path - make sure the first line of your script is this shebang line:
#!/usr/bin/env python
... and add $HOME/bin to your $PATH
Add a shebang in the start of your file like this #!/usr/bin/python
And make it executable
I do already have python installed, but when I used the python installation manager on windows, it did all of that for me, and I was wondering if there was some install manager for linux
Are u on Arch right?
yeah
"it did all of that for me"
What was "all of that"?
Just use pacman
idk, it just let me use "py" instead of python for my apps 😭
Oh an alias
On UNIX you don't even need the py
Are u using bash?
thinking about doing 1-2 leetcode problems daily from now on
kitty :3
maybe try some C++ for that too..
kitty because it sounds cute
some triton/CUDA and some math
Try out other sites too
if there was one called "bunny" I'd use that instead
should probably carve out 2 hours just to study on some stuff but i need it to be structured so i dont spend too long deciding what to study..
yeah maybe codeforces.. but probably best to do that once i have done more leetcode maybe
Isn't kitty a terminal emulator?
yeah
muda was asking about your shell, not the terminal emulator
Is there any significantly better alternative to kitty?
Welp it depends on what you are looking for
It's been a while since my desktop was linux; I used to use urxvt but I gather things have moved on.
Hi!
Hi!
Very hi!
ghostty
and actually supports sixel
Would say Alacritty but idk if he likes images in terminal or not
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Aight lemme learn python fr
Where do I start
With 'Automate the Boring Stuff with Python' ?
- Automate the Boring Stuff is a really good book for complete beginners and it's free to read online.
- If you prefer to watch video tutorials Corey Schafer's playlist is also really good.
- I also recommend Harvard’s free online course CS50P: Introduction to Programming with Python.
- Python Programming MOOC 2026 is an alternative online course with lots of integrated practice problems you can do directly in the browser.
Sixel's a minimum standard of care for me 🙂
i have a fondness for sixels
.topic
dives into an OpenVMS rabbithole
How could you use Python to help with writing a book? 🤔
if the book includes content sourced from somewhere else (such as Python source code), you could use Python to combine the content to make the final book
I do something like this for blog posts, documentation, and presentations
Now we just need a sixel based typesetting software to replace latex!
Hmm, I guess that’s a use case, it is pretty niche though
why do you ask about writing books?
I’ve just wanted to start writing, and I’m trying to find ways to tie it into things I already use/do
The Python docs
And the default for writing is writing books ig 🤷
what kind of writing will you do?
there are lots of other things to write. Books are a multi-year commitment. You might want smaller milestones
- Write a tool to help you organize your thoughts and organize the content of the book
- Something like asciidoc so you can generate html/pdf from the source of your book
- Stats about your vocabulary, overused words, opportunities for rephrasing, grammatical checks, etc.
Maybe some creative writing, maybe I’ll write about my interests and what I like about them and why, maybe my favourite types of bread, maybe complaining about media I think is so close to being amazing, but just falls short, I don’t really know
I just want to write :D
sounds like a blog
Writing stats would actually be great
I’ve thought about making a blog but I’m not skilled enough to write anything yet haha
Maybe one day
yeah, it can go quite far. Like which paragraph stands out with the shortest length, the most complicated sentences, etc.
And aside from tumblr, I don’t know the first thing about actually setting up a blog
you shouldn't pre-criticize yourself. Write something.
make your own static site generator
I could see such a tool being useful for obscuring the use of AI in writing (unethical btw)
you could
Hello guys i'am new member, i start to learn python in the same time i am in the school 42 i know the C but i'm not expert, do you know good website for learn pls ? thanks you for your help
it's not because you could that you should
You could count how many times specific hints that something is made by AI is used, then compare that to the average amount that a regular person uses them
there are some papers about how you can identify someone based on their writing style
Was just reading one about linking Reddit alt accounts
does it work?
I think if you’re going to use AI though, you really should just admit it and accept that some people (rightfully) don’t like their literature being mass produced by something that doesn’t think or feel
thanks you so much 
if you want to write, you wouldn't use AI to create the text.
All AI generated books are the most blatant cash grabs ever (imo)
I like writing. i have a goal of two blog posts a month. I write them and ask Claude to read them.
yes, exactly. We should talk about what you want to write.
I really want to talk about writing but I have a flight in like 7 hours and I haven’t slept at all 😭
Goodnight everyone :D
I think that the best thing for me to do is to learn to give up on the idea of what "writing" is and isn't, and just start putting letters on pieces of paper or characters on LCD displays
https://ojs.aaai.org/index.php/ICWSM/article/view/35920/38074 that's the one,
what would be the best game engine for a game thats like the way you see is like this
------]----[
------]----[
------]---o[
------]----[
------]----[
and its like story game and kinda like a text andventure right now im using visual studio code but i dont think i would be able to make the map thingy on anything that isnt the console so you cant really see it if you are playing it from like a website and its going to be hard to make the map thingy on a engine like godot so idk
thanks!
Thanks!
True story: decades ago, my wife said she wanted to be a writer, and she wondered what she should do. I said, "just write" and that surprised her. She has published four books.
https://doi.org/10.1609/icwsm.v16i1.19359 is specifically Reddit, but I think it's same technique as that second link which was X to Foursquare
Maybe consider a career as a motivational speaker?
In the same vein as Shia LaBeouf
Uh, have you been keeping up with news about Shia?
Nope
Just referencing an old... skit or whatever you'd call it
has he been charged or smth
Battery and alcoholism apparently
damn bro fell off hard
Anyone with knowledge of typer: I've defined a callback for common command options. I'd like to parse the same common options after the command. Anyone happen to know if that's possible without repeating the options everywhere?
my keyboard thinks that the center is the J key kek
I try here 🙂
so the rgb effects arent quite centered on my 60%
Same, same
atleast you got rgb i been running on a jedel k11 that cost me £5
Hello guys
just get a k617 fizz
What's web scraping?
sure there isnt much modding or openrgb support but it works
What about hash function?
in large quantities, or small ones
Ngl there should be a tag to hide blog websites when searching for something
What can it be used on?
you do know what SHA is right?
wdym?
A little yea
Like what can I do with those information I gather?
£40 😭 maybe its a worthable investment what do the keys sound like?
which hash function are you asking about?
you can use it in your progam
very clicky out of the box, i made it quiet thru a tape and foam mod
its easy to fix too, if the rgb breaks then just hold fn+esc for 3s and boom
fixed
same thing with the keys, and you can hotswap the switches
and it has navkeys thru fn
Whats the cheapest split mechanical keyboard?
so when held, wasd is the arrow keys
60% ?
yep
you mean SHA-256?
Ye
those are ways to "fingerprint" data: different data will be very very very unlikely to produce the same hash value
SHA-256 is a SHA-2 algorithm, btw
@strong chasm by fingerprinting data, ned means creating a kind of warranty seal in a way
So it's like a way to prove that you made it?
with the hash, you can verify that the file you recieved isnt a different one by checking the output of the SHA-256 function on your new file and checking if it matches the one that the credible source has sent
What if it was different?
no, more like a way to check if the data hasn't been tampered with
Then someone may have tampered with it
Like injecting malware
the publisher's SHA-256 hash would be different from the file's
aka what dementati said
Ooooh
lemme show you
but most people ignore it
So I should always check it before using it
Is there something that says "hey this file was made by me!"?
Like a signature
The hashsums are built such that minor changes to data (even a single bit) considerably changes the hash sum.
Yes, digital signatures are a thing.
i dont have a lot of knowledge about digital signatures, but yes
yes, a cheap way
So it's a way to show the authenticity of a software?
git gpg commit signing 
It's a way to prove the authenticity of any kind of information.
Hashsum is about integrity. You can verify that the file is intact. It does not tell you about anything about who made this. But if you combine it with encryption (using private and public key), the hashsums can be used to authenticate that the message can only originate from the ones with the keys.
~/demo> cat original.txt
original code
~/demo> cat original.txt | hash sha256
ad431af6ea495661e7ef50ecec3257b417152f5389d3bd25ed70e1bea94afb9b
~/demo> cat evil.txt
evil code
~/demo> cat evil.txt | hash sha256
9ab9eab0ebde187863cdc46e9fd45a486503150907797393b2220f02d5c65256
~/demo> { cat original.txt | hash sha256 } == { cat evil.txt | hash sha256 }
false```
heres a demo
Ooh ok I think I understand a little
Btw what do you use to create these?
your shell can create them
Ah ok
what are "these"?
if youve got powershell i think it's Generate-FileHash or something like that
The only problem with powershell is verbosity
I kinda like that they use curly brackets
I just started learning about hash and web scraping so I refer to them as "these"
Get-FileHash path-to-file
Thank you guys
Also, you can get Python to create them. See the hashlib module.
!doc hashlib
Source code: Lib/hashlib.py
This module implements a common interface to many different hash algorithms. Included are the FIPS secure hash algorithms SHA224, SHA256, SHA384, SHA512, (defined in the FIPS 180-4 standard), the SHA-3 series (defined in the FIPS 202 standard) as well as the legacy algorithms SHA1 (formerly part of FIPS) and the MD5 algorithm (defined in internet RFC 1321)...
SHA0 💀
Example:
[~/tmp/disco/zuzu]fleet2*> L
total 8
drwxrwxr-x@ 4 cameron staff 128 8 Mar 08:07 .
drwxrwxr-x@ 67 cameron staff 2144 8 Mar 08:03 ..
-rw-rw-r--@ 1 cameron staff 874 8 Mar 08:07 2d.py
-rw-rw-r--@ 1 cameron staff 453 8 Mar 08:10 2d2.py
[~/tmp/disco/zuzu]fleet2*> hashindex ls
blake3:75c38e97a1e718f56585504eba48578d115f4fcf204c7c990d4ce455b4cd400d ./2d.py
blake3:ae26d2a7cdb05aed89d5ba37eaed89a5d2401612bf7caf3a00b29ca8dd07fc5f ./2d2.py
The hashindex programme is a python script of mine, which reads and computes file content hashes.
Its also how passwords should be stored
You just see if hashed(users_password_input) == the existing hashed password and if so then it's the right password
password-store mentioned?
questoin, i was looking at the bots this server has, are the bots names reference to monty python and the holy grail or is it just medieval themed?
Monty python probably
The language was named after it after all
does any human deserve to live
??
bro is going thru existentialism
- yes, 2) this is off-topic, 3) I hope your day gets better
Yep
no rabbit of Caerbannog bot :c (edit had to fix the name, too long and i dont remember it well)
We still have quite a few knights left
its one of my fave movies so just curious lol
It is a fantastic movie
Rabbit? Like bunnies??
With nasty big pointy teeth
Lil bro u are 11 yrs old
and fangs
All the better to eat hay with :P
😭 what, no I just love bunnies
Oh wait are you talking Monty Python haha
Talking to blud saying "do humans deserve to live"
? I don’t understand
it was said its off topic and probably not a good idea to keep up that chat
Scroll up
just move on and forget it tbh
Try competitive programming
Oh 😭, yeah because Python has to be written by someone, and I know the snakes aren’t gonna do it themselves
Its like olympics for programming
Humans deserve to live because we invented python
@raw bramble
Yeah I saw
Some of them are like this
i would not recommend competitive programming
I am 40 years old
But mostly is a series of questions,going from easy to hard,that involves alot of things
because it not like actual programming, and won't build skills that help with actual programming
Sorta, ComPro (I’m not using the acronym leave me alone) is just lots of logic puzzles or math problems they need to solve, and it’s judged on how many they complete, how fast they complete and it often other factors like memory usage or execution time and things
Wont build skills?
".. that help with actual programming"
It’ll build skills, but they’re not skills you’d ever really need unless you’re working for the strictest company ever who gives you 2min deadlines for projects
I went to a programming competition once. Mainly seemed to demonstration that a group is slower than an individual.
I mean, compprog can be fun, you can do it for fun, and it's not completely unrelated to real programming, but it's not an effective method of learning software development
True
The only thing the comp prog helps with is that you actually have to sit down and plan your program on paper.
So many people just jump to writing code - both in basic comp prog and when trying to make their own projects - but it's great to at least spend bit of time to plan
if you want to go fast, go alone. if you want to go far, go together.
Planning is a difficult skill to learn though
Aye, because when the food runs out you can eat your companions.
I’ve started spending some time just commenting out the steps of my code before I make it
My impression is that you can do better as a group, but you need to be super coordinated, you can't just wing it
You’d need to be close to a hive-mind though to achieve that
More like, you need a strategy for how you distribute tasks and solve problems
Being able to program is a start
well, this is what software development practices aim to address; like the uncle bob, martin fowler, gang of four stuff. etc.
Its more on the CS part about math,dsa and more
You probably won't have much fun if you don't have decent general programming experience
There's a lot of DSA involved as well
It really depends on the difficult of the challenge you are given
No
Man I remember going to the finals but i didnt study DSA and I got fucked up
A hackathon is an event where you build a prototype of some project idea in a short amount of time, typically 24-74 hours.
It doesn't have to be in a group, and it doesn't have to be a competition.
you are saying that as if life is something that needs to be "deserved" rather than just a process of transfering matter and energy back and forth
life just happens, humans are one of the forms of it
Yes, I agree.
humans have self awareness on top of that
Yeah
it is
They may be asking for your subjective opinion rather than appealing to some objective standard.
i thought it was a rhetorical question, but answered it anyway
Taking rhetorical questions at face value is one of my favorite pastimes.
yeah, to be honest you are probably right because i guess it is obvious to any self aware human that the answer must be no
An egoistic one would say that
usually what people consider obvious is not obvious.
but also: are you ok? and this should be moved to off-topic.
as opposed to non-egoistic humans?
!ot
Please read our off-topic etiquette before participating in conversations.
I don't mean planning every single detail, but a lot of people don't even stop to think for a moment how to do something a smart way, they do it the bruteforce way and then come to #1035199133436354600 and ask why their program gives correct results but times out with the checker... Or just make their own project and do a needless recursion instead of a loop (some people's program menus are like that - rerun the menu function instead of looping...). Or they just write a lot of code and then don't really know what they wanted to do...
proof that all non-egoistic humans can fly by vacuous truth
But you can do it a smart way without a lot of planning, write the simplest code to get the minimum thing working, then see if you like it, try to imagine how understandable it is to other people, or if you had to come back to it, how it could be simpler, is it fast enough? Can I easily change specific parts later? Maybe this could go into a function and i can optimize that easily if I need to while keeping the overall flow clean.
If you learn something in the process you can even scrap it and start over and sort of naturally and casually end up on a better plan.
You could learn about UML (or other ones) diagrams to have a better visualization of what you want to build
mermaid >
Tests as specifications >
scribble whatever you want on paper as long as it gets the point across >
this is arguably way better
Yea leagues better or just make some flow in text that gets the point across. Whatever naturally communicates it to whoever you're making something for or working with.
The smart way is to just make it as fast as you can, then get better hardware if it’s slow, duhh
Code should NEVER be optimised
Are u sure?
the "duhh" in the previous message indicates that they are very sure. very non-sarcastic. no sarcasm detected.
i think lambdb is going to agree with you
As fast as you can is subjective though. Do I go for every micro optimization? What if I'm new? Do I exert all my effort on making it as fast as possible before I've even figured anything out? How am I measuring this?
Optimize when you are in need for it
Dont go for things you dont need
I can't tell with people sometimes ngl 😭
i myself have troubles with understanding people in general so this is relatable
i feel bad for you man, i fall for these as well
Learn Canary rather than qwerty, use Vim keybinds. Full line code completion. Anything to make you faster.
😔
Sarcasm on text is hard to spot
Become a professional stenographer, just make sure your typing speed is as high as possible and your code works in a way that’s the least effort for you
do stenography keyboards have normal keys for digits and special chars like punctuation
or they are chorded too
I don’t know, I want to learn stenography so I should probably look into that
It’s a really good question 🤔🤔🤔
Seriously, learn Vim, maybe learn a different keyboard layout like Colemak-DH or DVORAK,m
vim motions make text editing interesting
sometimes i stop to think about what the cool vim way to do something would be
Scientists should bring vim into human mind
i recently reversed some lines by doing :!tac
that was fun
I get annoyed at vim for my computer not having vim buttons instead of the regular keyboard buttons, but I get annoyed at typing in things because it’s so much effort to type without vim
where’s dW when you need it?
Vim is so good that I hate using editors of other software like Godot editor
vim or nvim ?
I think there’s a Vim plugin for Godot?
Nvim
Yes
Neovim just because I like its name more and its icon. I don’t use any of the Neovim features but it’s just cooler
Vim keybinds for the Godot?
Yeah, you can even get neovim in goody I think
i use lazy vim
i like it
Yes, yes you can
Solid choice
im thinking about using nano (jk)
i used nano for years before vim
tbh i hate it
I don’t know how I’m supposed to learn vim, but the few keybinds I know are super useful
I know 3 ways to exit vim
I stopped using it bc it was being slow and too many features that I didnt use
its funny i have a muscle memory to type nano file.py but then im used to vim keybindings so i just destroy the file with random characters
alias nano="vim"
The best way to learn vim is to have someone else watch you struggle
:qall
god send, doing this
export EDITOR=vim
Is there some actual vim tutorial practice thing like keybr or typemonkey?
bahaha it works i love it
i have alias print ="echo"
Vim tutor, yeah
Comes with vim
Why not using printf
theres also an adventure game for vim
Vim tutor is more of a walkthrough than a practice though
i code with python
Printf is a shell builtin
rly ?
And so is echo
idk tbh i can use echo but i made this as fun cmd only
printf(1), that is
printf(3) is a libc function in stdio.h
This remembered me that I "recreated" grep in c++
We need a !man command
reinvent the wheel
bruh watching guido present rn and he made all the question askers women! pretty cool feminist
How python have integration with C/C++ code?
what u mean ?
use cython
u mean that ?
the object model is flexible enough to represent arbitrary type layouts (just need the right header at the start, refcount and type pointer) and there are code paths to call arbitrary function pointers
Like in numpy,where the arrays is like from C iirc
numpy use cython
I used to make a practice of learnign a new keystroke every day - make a point of using the new one that day where possible.
Best practice is to use it in your projects
I tried and gave up since I was too unproductive lol
ultimately there is nothing special about C/C++ code except the fact that the normal compilers for it use a well known calling convention
you can interface with any executables
The problem:
Finding an idea for a project
it's easy
Lol don’t make a project just to learn vim
You should always have a side project that you passively work on, best way to improve
Unless the project is to implement vim.
True
repo name : vim learning
Python library for neovim
or you can start with vs code with vim extension
No way
stuff like libffi is fun
it does the things compilers do at compile-time, but at runtime
Making a smart compiler for C would be cool
what do you mean by "smart compiler"?
are the existing compilers stupid?
hello fix
happy 8 march 🥀
$ gcc
* compiler error *
$ sudo gcc
You're absolutley right! The code is actually valid. Here's what I'm going to do to make it compile...
Like finding patterns and optimizing it,finding errors (like heap pointers not being freed or things like it)
This made me cry a little
ai compilers 😭
compiler, make no mistakrs and make it fast, fix all bugs
Trying to understand memory management. I now have more questions than answers lol
Know of any good resources?
i dont have resources, but i have a tip : dont think that it is more complicated than it is.
And maybe ask the questions
you're not serious are you, AI compilers? 😐
llms can probably produce correct assembly for simple stuff
just dont expect it to be... smart
cant wait
tragedy in slow motion
ML is useful for heuristics in compilers though
but yeah making the actual compilation process AI driven is insanity
good luck certifying a stochastic process
How long does it take for you to forget to write code?
6 hours
I havent programmed in a while because of freaking school😭
Why so short
it certainly feels like 6 hours
If you're new probably a month or two
ooh yeah
How?
Elite skills require daily practice to maintain
i feel like i have lost all ability to code in the morning
Just like an athlete
I will probably take a gap year after high school to develop my programming skills
i forget certain specific things like some stdlib functions, but not the gist of it
programming (computer science) concepts are still in the head
NO
dont
Yes why not
why
"Gcc:/usr/programs/gpt.exe"
you cant brute force learning programming
Yeah probably
trying to program continuously for a year is not going to help
💔💔
you should try to pack in programming after school work
Not exactly brute force it
What happened to time management
it's built up slowly over a long period of time
Whats app
You dont need to learn fulltime
join a programming club or something
Yeah but l am entering medicine school and probably wont be enough time to program on the side
put in maybe 3-4 hours a week
Yeah l know
you are already guaranteed a place?
Yeah but like building projects is very unpredicatble
Not really working towards there though
💔
it's best you dont take things as guaranteed
Yeah
Oh yea I can see
Now l am thinking about it your kinda right
Do medicine students have a social life?
Dont you need a bachelors before you can enter medical school?
Yeah like 4 years of something l see
I dont even know though both my parents went to medicine school
Dude you can have hobbies while still studying fulltime
hi everyone
Yeah for real to think about it
You dont need to take a gap year to practice a hobby
Dont you need to study like 14 hours?
idk
depends what bsc you choose and your time management skills
yo PLEASE learn effective time management bros💔🙏😭literally the most important thing
I cant vro 🥀
.topic
!pypi imsosorry
Like this server, but in person
it's good to have 3-4 hours that is reserved just for programming every week
programming skills is built up over time
!pypi selenium
not 1 year of full time cramming
Those exist?
yea thats how i got started
though i guess the effectiveness differs between people
In my school there is one for game jam
your school?
I’ve not met someone my age who can program 😭🙏
(Whats your age bracket?)
Idk how to explain it bc idk if any other education systems has the same thing in my country
I mean in person
And it’s weird because I do Cybersec
the schools here all have some programming related club
In my school there is compprog, robotics,AI (all of them for olympics)
damn
just pick one of them
wdym
How old r u?
if people can hate for no reason i can love for no reason
❤️🩹
Unc
jk
you can probably find some kind of stem club in your local library
isnt all love for no reasons
if you already graduated then you can just program full time
They might be slow tho
Study and get your certificate equivalency
if you dont have a diploma
👴
Local libraries also have programs for things similar to that (at least where i live)
i'll be honest, as much as i would love to help, i don't have enough context about your background and situation for me to give you a prudent recommendation
and i dont have enough knowledge (or wisdom) to suggest anything either
Also, look for Python users groups and meetups
Irl users
Meetups are less formal
in my head meetups are also more about interaction between many people while conferences have speakers and listeners
or maybe thats just my bias because i only watch conference talks, not the whole conferences
i dont actually know what either words mean
Has anyone heard of obj to ascii project?
object to ascii?
Yeah .obj model files to ascii
Yeah
Well it renders to an ascii buffer
Where i think each character is a pixel but I might be wrong
a 2d projection of a 3d model, rendered in ascii?
Yeah
Conference are also a lot about interactions with people. Some people go to them (PyCon for example) and don't watch any talks live.
you could represent the 3d model in like multiple layers in a file
" " the low res no model
"." the low res model from a distance
me when the polygon triangulation
https://github.com/Vaxeral/sneeze/tree/main
I am trying to recreate it except with raytracing
Aye. I looks very cool.
┌────────────┐ ┌────────────┐
│ ├─┬────Files────► │
│ API Client │ │ │ Ingress S3 │
│ ├─┼──┐ │ │
└──────▲─────┘ │ │ └──┬────┬────┘
│ │ │ │ │
│ │ │ Files │
│ │ │ Created │ ┌──────────────┐
│ │ │ │ │ │ Unstructured │
│ │ │ ┌─▼─┐ │ │ Data │
│ │ │ Presigned │SNS│Files ┌─► Database │
├───────┼──┼───URLs──┐ └─┬─┘ │ │ └──────────────┘
│ │ │ + │ │ │ │
┌────▼─────┐ │ │ Data │┌──▼────▼─┐ │ ┌──────────────┐
│ ├─┘ │ └┤ ◄─┘ │ Structured │
│ Frontend │ │ │ Backend ◄───► Data │
│ ├────┴Requests──► │ │ Database │
└──────────┘ └─────────┘ └──────────────┘
```you can make diagrams like this
and put that into a docstring to make people suffer
Ah that's a better arrow glyph than I've been using.
The rendering for that is off
Works in a wide window.
it's still a little off, but i think it's good enough
Yeah I meant what i see on mobile on the site
I see it in discord though
Like the characters themselves dont line up top to bottom
But im on mobile so it doesnt matter
where ASCII?
not enough ascii
My hacks in this direction have this module docstring opening:
"Utilities to assist with ASCII art such as railroad diagrams; since these use Unicode box drawing characters and are better for diagrams such as railroad diagrams, this is neither ASCII nor art."
Though I added an optional ascii=True option which falls back to stuff like + and - and |
as far as i understand the basic way is to use characters with different "density" to represent grayscale intensity
is like 0, . is a small symbol, # covers much more
text in terminals is usually white on black background, and your brain will kinda average out the density of the white text in characters and see the image
making it represent the shape good is more complicated though
I bookmarked this recently, related https://alexharri.com/blog/ascii-rendering
Except when it's black on white, or green on black, or ...
Mola
ooh this is such a high quality article
i love the internet for that
Ascii rendering is probably the coolest thing ever
Like how you make letter be so similar to things that arent letters
Did you get my program to run?
You can make vertices rotate and it looks really cool
Just got to know a lil math.
What?
How does the bot work?
What bot?
Python?
The snake?
Does mypy scream at me if I illiterate over a dict but forgot to put .items()
you mean iterate, and it's ok to do for k in a_dict:
though it might not do what you want: it gives you the keys
For k, v in dict:
that doesn't do what you want.
you want: for k, v in dict.items():
Yeah, will mypy scream at me if i forgot .items() ?
maybe not, but it will fail at runtime in a few different ways
Is using freethreading python good for cpu bound tasks?
potentially
destructured assignment to a sequence of targets like k, v requires the value to be iterable
dict's are iterable over their key type
so, it will type error if the dict's key type is not an iterable type, but pass otherwise
though, if the usage of k and v dont follow the types that you get from iteration - you will get errors in their usage
usually for k, v in dict_: means the keys to dict_ is a tuple pair
usually it means you forgot .items(), especially with those names
but it's mostly in the form of something like x, y or i, j
yeah
those names are a big indicator of a forgotten .items()
name driven static analysis
applying the unwritten conventions of programming
It should be a lint warning for k, v in dict: but it's theoretically reasonable so you wouldn't want to error and block
the typechecker will catch it
Type checker wouldn't catch it.
why?
keys are often strings, which are Iterable[str], so it would do k: str, v: str
Because it's an iterable so you can do that. Having a key that can be unpacked is a possibility. I often do grids in dictionaries with the keys being the x, y coordinates.
sure. it'll catch some of the cases
>>> for k, v in {"xy": 1}:
... print(k, v)
...
x y
It might but I tend to doubt it. It's more suited to a linter as a warning because there are times when you do want to unpack the key.
what do you mean "it might"
ruff seems fine with it. =/
feels like something that should at least generate an "are you sure"
It depends on how well defined the dict is for the type checker. It also depends on whether the key is an Iterable that could be unpacked. If the key is a str, which is probably the most common type to use for a dictionary key, it wouldn't catch it because it's valid code.
yeah, it catches some of the cases
The only place you could catch it is with a linter. I didn't say that there are any that would.
also: yet another instance of string being iterable causing problems
/nod
If you have d: dict[int, str] it would.
that would be one of the cases, yes
unpacking iterables of unknown element sizes in a for loop is definitely a lint to consider
its somewhat fine in a single case because its not unreasonable to expect someone to be able to derive that the size is that exact value from some other information
but expect the whole thing to be it? thats too much
But the most common is d: dict = {} or d: dict[str, Any] = {} and it wouldn't in either of those.
vibes based static analysis
those would not be included in the cases. also, i would agree that string keys are the most common, but i think in many cases there is information able to be inferred about the dict
For my Grid I define d: dict[tuple[int, int]: str so that wouldn't be caught by a type checker although it would probably cause a RuntimeError because I wouldn't have the expected value.
The python type system is insufficiently detailed to handle fixed-length iterables
Your type checker may or may not read through that and infer what it can from the actual code
It would be nice to be able to type that deeply into program behavior, but things are messy enough as it is tbh
This particular case doesn't feel too bad as a type checker extension: when do you actualyl want to unpack a dictionary key in a loop? pretty much never
I might if the key is a tuple such as grid coordinates. But I'm more likely to do for (x, y), v in d.items() in that case.
Or just a lint rule requiring keys, values, or items.
i thought about special casing something like __iter__ -> tuple_iterator[*Ts]
but idk
The difference between iterable and unpackable raises it's head
although unpacking lists and stuff has similar caveats
Maybe just a lint for unpacking strings?
very rare to want to do that
!zen 5
Sparse is better than dense.
!zen 6
Readability counts.
!zen 4
Flat is better than nested.
!zen
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Suggest more topics here!
BASIC on a Commodore-64
C#
roblox luau
How do i do multi threading on pyrhon?
That depends on what you want to do.
perl, technically
I'm sorry.
BASIC, technically
Technically?
multithreading for concurrency: asyncio
multithreading for nonblocking: threading
multithreading for isolation: concurrency.interpreters
multithreading for performance: multiprocessing
Python doesn't have the classic multithread model of other languages due to a variety of data-safety guarantees it provides that they don't. What "threads" in java do are somewhere between threading and multiprocessing
I learned Python the next year and was never serious in it
I have a PEP draft i'd appreciate feedback on. I don't know whether i'll actually publish this yet so feel free to leave some opinions
is it that bad?
Are we up to 9999 already?
I uh... I actually thought this was already a thing
I didn't want to assign it a number because again, not sure whether i'll publish it
that's a good sign, lol. that means it's intuitive
I know I've used...
I think I'm thinking of async with
yeah, adding to the collection of async-prefixed things
I think yield from should be forbidden in async generators and permitting async yield from to be used with sync generators inside async generators
why?
The abstract doesn't explain what the PEP is about. It starts, "This would be valid with this PEP...". I think you need to add a paragraph or two about what the change is to the abstract ahead of that.
Because having both available is somewhat confusing and prone to footguns. The only time you'd want to yield from in an async generator is when you have a sync generator that's "not blocking" whatever that means, but that's a semantic detail. async yield from transmuting to an async yield makes a lot more sense because yield from is already suspending execution and that matches gaining an async or await tag to indicate it is in fact such a break in execution
Additionally, this design flaw has come up on StackOverflow.
I would say "design decision", not "design flaw". Your audience is full of people who made that decision, don't offend them.
I can see a lot of cases where someone accidentally yield from's when they're supposed to async yield from and doens't realize it, and IIRC current tasks let you do that..
I might be wrong
I mean, async for doesn't work with synchronous iterators. to my knowledge, there's no existing construct that works on both sync + async. I think it'll be a hard sell here.
!e ```py
import asyncio
async def a(n=1):
if n == 4:
return
await a(n=n+1)
async def main():
for i in a():
print(i)
asyncio.run(a())
don't think i've seen a coroutine with yield in it in a long time
:warning: Your 3.14 eval job has completed with return code 0.
[No output]
This is the problem
Honestly, maybe it should, but the circumstances are a bit different because a for loop is a for loop not a suspension mechanism
not disagreeing, but I think that's beyond the scope of this proposal. this seems like a more fundamental issue with async, rather than yield from
I don't see the benefit of async yield from. I do see the benefit of allowing async functions to yield from synchronous generators though.
That's valid, but the problem is permitting yield from in an async generator leads to ambiguity/footguns where you can yield from any coroutine to strange results
!e ```py
import asyncio
async def a(n=1):
if n == 4:
return
await a(n=n+1)
def main():
yield from a()
print(*main())
:x: Your 3.14 eval job has completed with return code 1.
001 | /home/main.py:10: RuntimeWarning: coroutine 'a' was never awaited
002 | yield from a()
003 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
004 | Traceback (most recent call last):
005 | File [35m"/home/main.py"[0m, line [35m12[0m, in [35m<module>[0m
006 | [31mprint[0m[1;31m(*main())[0m
007 | [31m~~~~~[0m[1;31m^^^^^^^^^[0m
008 | File [35m"/home/main.py"[0m, line [35m10[0m, in [35mmain[0m
009 | yield from a()
010 | [1;35mTypeError[0m: [35mcannot 'yield from' a coroutine object in a non-coroutine generator[0m
Interesting.
I don't think it'll let you yield from a coroutine. values yielded from an async generator are wrapped in a special sentinel object.
hm, why not? there are plenty of reasons you might want to do that
https://github.com/cython/cython/issues/6614 this might also be worth looking at, although idk if it's relevant
Can i string filters in python to geter without forcing them to materialise first?
I think that's just cython having different semantics
Such as? And could those be written as synchronous generators?
Looking into the source, it doesn't let you yield from a standard python coroutine, but it works with anything coroutine-like
I'm also not 100% sure there are no security implications here, FWIW.
for example, if you were delegating an HTTP response:
async def make_request():
async with http_request("https://whatever.com", settings=...) as res:
async yield from res.content()
inst(GET_YIELD_FROM_ITER, (iterable -- iter)) {
/* before: [obj]; after [getiter(obj)] */
PyObject *iterable_o = PyStackRef_AsPyObjectBorrow(iterable);
if (PyCoro_CheckExact(iterable_o)) {
/* `iterable` is a coroutine */
if (!(_PyFrame_GetCode(frame)->co_flags & (CO_COROUTINE | CO_ITERABLE_COROUTINE))) {
/* and it is used in a 'yield from' expression of a
regular generator. */
_PyErr_SetString(tstate, PyExc_TypeError,
"cannot 'yield from' a coroutine object "
"in a non-coroutine generator");
ERROR_NO_POP();
}
iter = iterable;
DEAD(iterable);
}
!pep 492 for the co_iterable_coroutine
there's an opcode somewhere in there that wraps the object, so I'm relatively sure it won't let you accidentally await something
And is the current implementation that much more difficult?
basically the early version of async there
difficult, no. but there are drawbacks to just using an async for. we added yield from in the first place to get proper subgenerator delegation semantics.
IIRC Chris Neugebauer did a talk where he demonstrated doing async in Python 1.6 (IIRC he stopped there because he ran out of time to finish writing the talk.)
could you elaborate on this?
For stuff like futures and tasks I don't see it existing. You can pass anything into a yield from and while base coroutines are predictable futures are just an interface, and they deliberately support being yield from'd
Right. But I don't think that's going to be a convincing argument.
Lib/asyncio/futures.py lines 292 to 301
def __await__(self):
if not self.done():
self._asyncio_future_blocking = True
yield self # This tells Task to wait for completion.
if not self.done():
raise RuntimeError("await wasn't used with future")
return self.result() # May raise too.
__iter__ = __await__ # make compatible with 'yield from'.```
Maybe said backwards compatibility could be removed, I guess
But this would mean giving yield from in an async context different behavior than in a sync context regardless
at the opcode level, yield from in an async def is not the same as await. there's a special object that wraps the yielded value before its ever sent to disambiguate with coroutines.
I think that there are enough foot gun potentialities in here to have possible security implications. I'm not familiar enough with the underlying code and changes that would be required to give something more specific than a gut feeling and instinct after working in the security industry for a while.
Oh, I see. No, that wasn't my concern although that is a valid concern but I'm assuming there is a wrapper there. My concern is someone will forget an await:
async other_generator():
yield 1
async def generator():
yield from other_generator()
or will accidentally pass in a future instead of their intended generator (because a library returned a future instead of a standard coroutine and they didn't know because they behave the same)
the reference implementation raises an exception that says Did you mean 'async yield from'? for that example
yield from then grows two separate semantics in two separate environments: for backwards compatibility it must yield from the coroutine itself (to support generator coroutines) but for async generators it must also yield from the contents of the coroutine, and it can't do both
It seems like async yield from is making something that is already complex even more so.
it does do both, it wraps it in a special object like i've said
But how do you know which it should be?
you don't need to, python handles it for you
class MyFutureObject():
def __iter__(self):
print("Does future stuff")
class MyGeneratorObject():
def __iter__(self):
print("does generator stuff")
How do you tell apart these two cases for yield from?
hi i need help, my code in python x app is not working even though it shows the same output as the desired one
you await one, you yield from the other
You can yield from futures
I recommend opening a thread in #1035199133436354600
in old-style coroutines, yeah, but i'm not sure how that applies here
i think they might take a week or so to reply
Usually not.
ok hopefully
PyObject *
_PyAsyncGenYieldFrom_New(PyThreadState *tstate, PyObject *iterable)
{
assert(tstate != NULL);
assert(iterable != NULL);
_PyAsyncGenYieldFrom *yield_from = PyObject_GC_New(_PyAsyncGenYieldFrom,
&_PyAsyncGenYieldFrom_Type);
if (yield_from == NULL) {
return NULL;
}
if (!Py_TYPE(iterable)->tp_iter && PyAsyncGen_CheckExact(iterable)) {
_PyErr_Format(tstate, PyExc_TypeError,
"%T object is not iterable. Did you mean 'async yield from'?",
iterable);
return NULL;
}
PyObject *iterator = PyObject_GetIter(iterable);
if (iterator == NULL) {
return NULL;
}
yield_from->agyf_iterator = Py_NewRef(iterator);
_PyObject_GC_TRACK((PyObject *)yield_from);
return (PyObject *)yield_from;
}
Wait a minute, that's not python
It's Python source code 🙂
If you pass an instance of
class MyFutureObject():
def __iter__(self):
print("Does future stuff")
``` into
```py
async def generator():
yield from MyFutureObject()
It passes down into getiter, then your generator will execute the future in the style of an old yield coroutine future, yielding the future's intermediate yields instead of awaiting it
I don't have the time at the moment to build the demo version of python and run it myself, but it shouldn't be hard for you to test that
if it doesnt' blow up, then I guess I'm wrong
give me a moment to cosntruct a full test case though
the values returned by the tp_iternext are wrapped in the special thing. python will actually yield the future values rather than awaiting it. it's kind of difficult to wrap your head around
No, I get that, but that's the problem: they shouldn't be
or should they?
It's a footgun, what the person meant was yield from await MyFutureObject()
is this an example of what you're thinking of?
import asyncio
async def run():
yield from asyncio.ensure_future(asyncio.sleep(1))
this raises a RuntimeError: await wasn't used with future
But would it with the suggested change? And if it doesn't, would it work as expected?
without the suggested change you get a SyntaxError for using yield from in an async def
Yes, that seems a valid example
So if you try to yield from a future it would raise a RuntimeError?
Because you are iterating into the future itself and basic python futures have an error check for that
This will let us return a coroutine from a generator then do async yield from await (yield from x())
def __await__(self):
if not self.done():
self._asyncio_future_blocking = True
yield self # This tells Task to wait for completion.
if not self.done():
raise RuntimeError("await wasn't used with future")
return self.result() # May raise too.
__iter__ = __await__ # make compatible with 'yield from'.
On the second loop through
But that means you do get a random future dropped into your loop for the first iteration, which can error in weird places and is the core problem (or more than that with alternate implementations)
this is true for sync generators, FTR. you need to decorate it with @types.coroutine to use the legacy syntax
This is solveable by checking for the presence of __await__ in yield_from and erroring if it's present
As that would prevent accidentally fumbling into coroutine generator implementation details when you miss an await call
although I still don't know if there aren't any valid use cases where you want an object both iterable in a non-coroutine sense and awaitable in a coroutine sense
I think supporting that one is a bad idea, because it's already jank enough if you do that and this would be limited to the new syntax anyway
this seems like stuff that will likely be handled by a type checker anyway
That is not a solution. That is passing off responsibility.
import asyncio
async def steps():
await asyncio.sleep(0.25)
await asyncio.sleep(0.25)
await asyncio.sleep(0.25)
async def generator():
yield from asyncio.ensure_future(steps())
async def run():
async for i in generator():
print(i)
No, I think relying on the type checker for handling jank cases of intersection behavior is valid
Not everyone uses a type checker.
I think this is a valid test case? It should throw out several values before eventually erroring..
practicality beats purity. you could pretty much reject every proposal on the basis that "someone might accidentally write a bug using this"
haskell meanwhile:
reference implementation says RuntimeError: await wasn't used with future again
Someone's gonna write a bug with it. The question is are we handing them a foot gun with this?
oh, there was one <Task pending name='Task-2' coro=<steps() running at /home/peter/develop/cpython/a.py:3>>
Yes
that's the problem
You end up sending a future through the loop as the loop variable for at least one step before you crash
I don't think it's a very big problem if it throws a big error at you right after
The problem is you're not going to get that error: you're going to get a different one, probably a typeerror
But right after could be a while. And, as @jagged belfry says, the error is likely to be unhelpful.
Like if generator() is supposed to return ints, then you'll get a cannot add future and int
I wouldn't say unhelpful, just non-obvious
I'm learning python right now I think I'm at intermedate level, I also know html, css some js some c# and some game dev but I'm getting back into it fresh after a long time
What project should I do
Whats the most recent thing you've made?
!res
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
import asyncio
async def steps():
await asyncio.sleep(0.25)
await asyncio.sleep(0.25)
await asyncio.sleep(0.25)
return [1, 2, 3]
async def generator():
yield from asyncio.ensure_future(steps())
async def run():
total = 0
async for i in generator():
total += i
print(total)
Here's a better example, this should provoke the typeerror
Mostly web development Shopify Liquid
Theme features and such for the store I work on
this seems like a toe stub gun, if anything
Are you looking to build something with Python or ?
Maybe? But maybe worth addressing in the pep regardless?
Sorry, I don't mean to be combatitive
Yeah I need a project idea, I'm thinking maybe a task manager Python Flask
Something like trello but simple
no worries, it's helpful feedback. i'm not sure what I would even add, though. "it's possible to write bad code with this PEP" seems kind of obvious