#python-discussion

1 messages · Page 333 of 1

oblique spindle
#

Understanding low level things is useful for curious people but not knowing it is not a big deal.

pastel sluice
#

@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

strange girder
#

the not-from-scratch way is to use pydantic or msgspec

raw bramble
#

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

crisp jay
#

Computers are essentially just bunch of 0 and 1 manipulated in different ways

prime sorrel
#

remember folks, whenever you thinking learning low level is the only way to make money, remember that bill gates wrote DONKEY.BAS.

dusty ember
#

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).

raw bramble
eternal loom
#

9.0%4
Out[22]: 1.0

-9.0%4
Out[23]: 3.0

how ?
can anyone tell what's the logic behind this

oblique spindle
#

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

raw bramble
crisp jay
#

The strategy is building your own wheel 💪

raw bramble
prime sorrel
#

im very aware of the strategy.

oblique spindle
prime sorrel
#

but i dont ahve time to do all that, its a poor choice of tool for the job in hand

raw bramble
#

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

oblique spindle
#

The official syllabus for computer stuff is so bad the last thing I remember studying in my school is www and html with styling 💀

lapis idol
#

im looking for an expert of python for a new project. If u r one, plz send me a dm.

strange girder
crisp jay
#

Idk web development seems boring

raw bramble
oblique spindle
#

Css was never taught to me.

raw bramble
#

my school taught html and visual basic, but the teachers didn't have the best grasp on much else

lapis idol
#

so someone can help for a project plz

raw bramble
#

no need to ask to ask :P

ornate wren
prime sorrel
#

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!

raw bramble
prime sorrel
#

used to get bullied for it. but now it's 'retro' people are starting to say its actually somewhat 'cool.

raw bramble
#

I'm going to guess .NET, but that's entirely a guess based on vibes, it is equally as likely have been VB6

raw bramble
prime sorrel
raw bramble
#

I can't be mean to people in real life, I don't have a real life 😢

prime sorrel
#

i figured

raw bramble
#

aw man

prime sorrel
#

also you do realise we are in a python room. lol

#

its not exactly sega megadrive assembly

eternal loom
raw bramble
#

Visual Basic itself is a bit outdated nowadays

prime sorrel
#

visual basic 6 did me well.

#

as i said yesterday, i just cant continue with windows.

ornate wren
prime sorrel
#

visual basic's biggest flaw being, windows

raw bramble
prime sorrel
#

i'd strip it down to a black screen write terminals, do opengl graphics and stuff, make it procedural. lots of fun and learning

ornate wren
#

vb.net is useless when you have C#

prime sorrel
#

oh and also i got it free, i think its OK to confess.. it was stolen many years ago

raw bramble
#

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

raw bramble
autumn pelican
#

Oh boy

#

You're gonna have a lot of fun

raw bramble
#

I've had experience with Linux before, just not on my home computer

autumn pelican
#

Ah good

raw bramble
#

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

prime sorrel
#

no, comma, new item: do opengl graphics and stuff.

#

pygame is debatable though, aye?

craggy willow
crisp jay
craggy willow
#

opengl graphics in terminals

prime sorrel
#

ah okay

crisp jay
craggy willow
#

it is interactive, you can click on it and make a new thingy appear, i think it shows in the video

raw bramble
#

I've heard that Vulcan is better for modern, high-end devices?

raw bramble
lucid agate
#

i’m switching to MechE or Civil that’s it

#

i can’t keep living like this😩😩😩😩

raw bramble
#
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?

robust ledge
#

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.

raw bramble
#

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

robust ledge
#

A json file is one way to store structured data. Sounds like a plan.

raw bramble
#

How do I convert the json string into the dataclasses?

robust ledge
#

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.

raw bramble
#

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

robust ledge
#

So you'd need to iterate through the list and then create an instance of your Person dataclass for each item.

raw bramble
#

you can do __as_dict__ in a dataclass, right? is there a way to make a __from_dict__

edgy krakenBOT
#

Hey @pure grotto!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
robust ledge
#

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)

raw bramble
#

splat?

silver plover
#

(Dont use dataclasses_json, which is overly complicated and unmaintained for a few years)

raw bramble
#

but also damn, google, and all search engines have gotten way worse recently

silver plover
raw bramble
#

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

robust ledge
#

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.

raw bramble
#

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 :(

robust ledge
#

You do you, there is no judgement here. Just suggesting breaking off a smaller piece.

crisp jay
patent kestrel
#

realpython slander

raw bramble
#

How would you work with json and non-data classes

crisp jay
raw bramble
crisp jay
#

Imagine needing to login in a website to see basic things of Python

raw bramble
crisp jay
#

That the official docs do it for free

spice hill
#

yeah the login banner is terrible. but I think it won't show up if you use incognito mode

raw bramble
#

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

velvet trout
#

Official python docs solos every other tutorial

bronze dragon
robust ledge
raw bramble
past shard
#

Is anyone of you here familiar with whatsapp api??

robust ledge
raw bramble
#

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.

bronze dragon
raw bramble
#

actually yeah no you're right 😭

#

What am I thinking. Start with the basics

robust ledge
#

Ah peer pressure.

raw bramble
#

My biggest issue has always been knowing enough about things to move on without fully understanding them

robust ledge
#

If you let Pydis drive, you'll be loading pydantic base models for your very starter cli app.

#

((this is humor))

spice hill
# velvet trout Official python docs solos every other tutorial

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

raw bramble
#

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

robust ledge
raw bramble
#

oops yeah 😭 I meant it to be a list of dicts

#

I'll just use a single dict rn though

robust ledge
#

Yup, the edited will read the file as a string. That's where json.load() or json.loads() comes in.

patent kestrel
#

Person(**your_dict) will make an instance of Person assuming the dict has all the attributes

raw bramble
#

what's the difference between .load() and .loads() ?

pastel sluice
velvet trout
raw bramble
#

oh that makes sense :D

#

thank you

velvet trout
#

Yeah. I was like you, scratching my head about what it could be.... Then asked here, people replied and then oh that makes sense!!!

worn moth
#

foo = json.load(open("foo.json", "r")) so convenient

supple dome
#

is tkinter a good library to start with?

#

im beginner

pulsar saffron
#

sup

raw bramble
#

@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)
raw bramble
#

yes :D

robust ledge
#

Great start then!

raw bramble
#

I can create new data, but I'm thinking about editing existing data, and deleting data now.

robust ledge
#

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.

raw bramble
#

alright :P

robust ledge
#

or carry on and figure out editing. :P You're driving.

unborn heron
#

hello

#

can anyone remind me how to make it so that the printed text can go down a line like
this

humble jungle
#

\n maybe?

unborn heron
#

Oh ye that thxz

oblique spindle
#

🤣

unborn heron
crisp jay
zealous lion
unborn heron
#

Honestly couldn't care ik i never learning that stuff

crisp jay
#

Everyone is capable of learning

unborn heron
#

no no

#

not like i cant

#

i mean i wont

crisp jay
oblique spindle
heady moat
#

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

crisp jay
#

Google collab?

heady moat
#

Yeah

unborn heron
#

google collab has a coding syste>'

#

?*

crisp jay
heady moat
#

Yeah google colab

unborn heron
#

Whenever im on my phone i usually just use notepad

rocky heath
#

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

heady moat
#

I got a keyboard attached to ipad so its just missing the software at this point

zealous lion
crisp jay
rocky heath
heady moat
oblique spindle
zealous lion
#

no worries

rocky heath
#

i did that wrong

#

one sec

hearty nacelle
#

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()

rocky heath
crisp jay
#

!paste

edgy krakenBOT
#
Pasting large amounts of code

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.

rocky heath
surreal knot
hearty nacelle
rocky heath
#

Link, thanks

#

What do you guys think?

#

@crisp jay

crisp jay
#

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
rocky heath
#

oooo whats that?

surreal knot
rocky heath
rocky heath
crisp jay
#

Or the logic of your code has a case for mouse_position being equal to rect_counter?

rocky heath
crisp jay
#

Ok

brittle bear
#

Can yall give me some begginer python projects that will make me come back the next
Day to make upgrades or smthn

rocky heath
crisp jay
rocky heath
# crisp jay What is this project?

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.

rocky heath
#

i linked*

rocky heath
humble jungle
rocky heath
copper yew
#

.

humble jungle
#

Idk I remember this being a problem where the events were poped off and the order was reversed so it didnt resize correctly

copper yew
#

i dont now

#

what it mean

tulip cedar
#

alright

raw bramble
#

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

crisp jay
#

Run with sudo ofc

#

Oh you want to run without calling python

granite wyvern
# raw bramble How am I meant to install python on arch? I used yay for it, but I just realised...

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 .py extension
  • 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

crisp jay
#

Add a shebang in the start of your file like this #!/usr/bin/python

#

And make it executable

raw bramble
raw bramble
#

yeah

granite wyvern
#

"it did all of that for me"
What was "all of that"?

crisp jay
#

Just use pacman

raw bramble
granite wyvern
crisp jay
#

Are u using bash?

restive pecan
#

thinking about doing 1-2 leetcode problems daily from now on

raw bramble
#

kitty :3

restive pecan
#

maybe try some C++ for that too..

raw bramble
#

kitty because it sounds cute

restive pecan
#

some triton/CUDA and some math

crisp jay
raw bramble
#

if there was one called "bunny" I'd use that instead

restive pecan
#

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..

restive pecan
granite wyvern
raw bramble
#

yeah

crisp jay
#

Kinda slow tbh

granite wyvern
#

muda was asking about your shell, not the terminal emulator

raw bramble
#

Is there any significantly better alternative to kitty?

crisp jay
granite wyvern
#

It's been a while since my desktop was linux; I used to use urxvt but I gather things have moved on.

hot totem
#

Hi!

raw bramble
hot totem
craggy willow
#

and actually supports sixel

crisp jay
bold maple
#

!resources

edgy krakenBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

bold maple
#

Aight lemme learn python fr

#

Where do I start

#

With 'Automate the Boring Stuff with Python' ?

golden mortar
granite wyvern
cerulean ravine
#

i have a fondness for sixels

manic flare
#

.topic

verbal wedgeBOT
#
**What's your favorite Python related book?**

Suggest more topics here!

manic flare
#

Python Crash Course by Eric Matthes

#

Learned Python from it

cerulean ravine
#

dives into an OpenVMS rabbithole

raw bramble
#

How could you use Python to help with writing a book? 🤔

cerulean ravine
#

I do something like this for blog posts, documentation, and presentations

silver plover
#

Now we just need a sixel based typesetting software to replace latex!

raw bramble
cerulean ravine
raw bramble
crisp jay
raw bramble
cerulean ravine
cerulean ravine
kind thicket
# raw bramble And the default for writing is writing books ig 🤷
  • 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.
raw bramble
# cerulean ravine what kind of writing will you do?

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

cerulean ravine
raw bramble
raw bramble
#

Maybe one day

kind thicket
raw bramble
#

And aside from tumblr, I don’t know the first thing about actually setting up a blog

cerulean ravine
kind thicket
raw bramble
mellow glacier
#

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

kind thicket
#

it's not because you could that you should

raw bramble
kind thicket
silver plover
kind thicket
raw bramble
mellow glacier
#

thanks you so much pithink

cerulean ravine
raw bramble
cerulean ravine
#

I like writing. i have a goal of two blog posts a month. I write them and ask Claude to read them.

cerulean ravine
raw bramble
#

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

silver plover
#

Oh that's not it. That's Portuguese

raw bramble
#

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

silver plover
hardy tendon
#

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

kind thicket
cerulean ravine
silver plover
golden mortar
#

In the same vein as Shia LaBeouf

silver plover
golden mortar
#

Just referencing an old... skit or whatever you'd call it

sullen dust
golden mortar
#

Battery and alcoholism apparently

sullen dust
#

damn bro fell off hard

hearty nacelle
#

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?

steel whale
#

my keyboard thinks that the center is the J key kek

cerulean ravine
steel whale
#

so the rgb effects arent quite centered on my 60%

golden mortar
sullen dust
strong chasm
#

Hello guys

steel whale
strong chasm
#

What's web scraping?

steel whale
#

sure there isnt much modding or openrgb support but it works

steel whale
#

thru programs

strong chasm
steel whale
#

in large quantities, or small ones

crisp jay
#

Ngl there should be a tag to hide blog websites when searching for something

strong chasm
steel whale
steel whale
strong chasm
strong chasm
sullen dust
cerulean ravine
steel whale
steel whale
#

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

crisp jay
#

Whats the cheapest split mechanical keyboard?

steel whale
#

so when held, wasd is the arrow keys

crisp jay
strong chasm
#

2

steel whale
steel whale
strong chasm
#

Ye

cerulean ravine
# strong chasm Sha 3

those are ways to "fingerprint" data: different data will be very very very unlikely to produce the same hash value

hearty nacelle
steel whale
strong chasm
steel whale
#

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

steel whale
golden mortar
#

Like injecting malware

steel whale
#

aka what dementati said

strong chasm
#

Ooooh

steel whale
#

lemme show you

sullen dust
#

but most people ignore it

strong chasm
#

So I should always check it before using it

crisp jay
#

Like a signature

hearty nacelle
#

The hashsums are built such that minor changes to data (even a single bit) considerably changes the hash sum.

golden mortar
steel whale
steel whale
strong chasm
gleaming knoll
#

git gpg commit signing tada

golden mortar
hearty nacelle
#

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.

steel whale
#
~/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

strong chasm
#

Ooh ok I think I understand a little

strong chasm
steel whale
strong chasm
#

Ah ok

cerulean ravine
steel whale
#

if youve got powershell i think it's Generate-FileHash or something like that

crisp jay
crisp jay
#

I kinda like that they use curly brackets

strong chasm
steel whale
#

Get-FileHash path-to-file

strong chasm
#

Thank you guys

granite wyvern
#

!doc hashlib

edgy krakenBOT
crisp jay
#

SHA0 💀

granite wyvern
# strong chasm Thank you guys

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.

autumn pelican
#

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

crisp jay
tardy flax
#

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?

autumn pelican
#

The language was named after it after all

hardy rose
#

does any human deserve to live

autumn pelican
#

??

tardy flax
#

bro is going thru existentialism

cerulean ravine
golden mortar
tardy flax
#

no rabbit of Caerbannog bot :c (edit had to fix the name, too long and i dont remember it well)

golden mortar
tardy flax
#

its one of my fave movies so just curious lol

golden mortar
#

It is a fantastic movie

golden mortar
crisp jay
#

Lil bro u are 11 yrs old

tardy flax
#

and fangs

raw bramble
raw bramble
#

Oh wait are you talking Monty Python haha

crisp jay
raw bramble
tardy flax
#

it was said its off topic and probably not a good idea to keep up that chat

crisp jay
tardy flax
#

just move on and forget it tbh

crisp jay
#

Try competitive programming

raw bramble
# crisp jay Scroll up

Oh 😭, yeah because Python has to be written by someone, and I know the snakes aren’t gonna do it themselves

crisp jay
#

Its like olympics for programming

tame hinge
#

Humans deserve to live because we invented python

crisp jay
raw bramble
crisp jay
#

Some of them are like this

cerulean ravine
#

i would not recommend competitive programming

hardy rose
crisp jay
#

But mostly is a series of questions,going from easy to hard,that involves alot of things

cerulean ravine
#

because it not like actual programming, and won't build skills that help with actual programming

raw bramble
#

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

cerulean ravine
raw bramble
#

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

granite wyvern
golden mortar
#

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

harsh swallow
#

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

cerulean ravine
raw bramble
granite wyvern
raw bramble
#

I’ve started spending some time just commenting out the steps of my code before I make it

golden mortar
raw bramble
golden mortar
raw bramble
#

Being able to program is a start

hardy rose
crisp jay
#

Its more on the CS part about math,dsa and more

golden mortar
#

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

raw bramble
#

It really depends on the difficult of the challenge you are given

golden mortar
#

No

crisp jay
#

Man I remember going to the finals but i didnt study DSA and I got fucked up

golden mortar
#

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.

gleaming knoll
# hardy rose does any human deserve to live

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

golden mortar
#

Yes, I agree.

hardy rose
crisp jay
#

Yeah

pallid garden
#

it is

golden mortar
cerulean ravine
golden mortar
hardy rose
cerulean ravine
cerulean ravine
hardy rose
cerulean ravine
edgy krakenBOT
harsh swallow
# raw bramble Planning is a difficult skill to learn though

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...

gleaming knoll
#

proof that all non-egoistic humans can fly by vacuous truth

tame hinge
# harsh swallow I don't mean planning every single detail, but a lot of people don't even stop t...

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.

crisp jay
steel whale
#

mermaid >

tame hinge
#

Tests as specifications >

gleaming knoll
steel whale
tame hinge
#

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.

raw bramble
#

Code should NEVER be optimised

crisp jay
gleaming knoll
# crisp jay Are u sure?

the "duhh" in the previous message indicates that they are very sure. very non-sarcastic. no sarcasm detected.

rare gazelle
tame hinge
# raw bramble Code should NEVER be optimised

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?

crisp jay
#

Dont go for things you dont need

rare gazelle
#

his name is esoteric

#

of course he's bbeing sarcastic

tame hinge
gleaming knoll
rare gazelle
raw bramble
crisp jay
raw bramble
gleaming knoll
#

do stenography keyboards have normal keys for digits and special chars like punctuation
or they are chorded too

crisp jay
#

The vim keybinds are right

#

Vim motions is goated

raw bramble
#

It’s a really good question 🤔🤔🤔

#

Seriously, learn Vim, maybe learn a different keyboard layout like Colemak-DH or DVORAK,m

gleaming knoll
#

vim motions make text editing interesting

#

sometimes i stop to think about what the cool vim way to do something would be

crisp jay
#

Scientists should bring vim into human mind

gleaming knoll
#

i recently reversed some lines by doing :!tac
that was fun

raw bramble
#

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?

crisp jay
#

Vim is so good that I hate using editors of other software like Godot editor

lilac grove
#

vim or nvim ?

raw bramble
#

I think there’s a Vim plugin for Godot?

crisp jay
raw bramble
# lilac grove vim or nvim ?

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

stray field
raw bramble
raw bramble
crisp jay
lilac grove
#

im thinking about using nano (jk)

wet fox
#

i used nano for years before vim

lilac grove
raw bramble
#

I don’t know how I’m supposed to learn vim, but the few keybinds I know are super useful

stray field
#

I know 3 ways to exit vim

crisp jay
#

I stopped using it bc it was being slow and too many features that I didnt use

wet fox
#

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

stray field
#

The best way to learn vim is to have someone else watch you struggle

wet fox
stray field
raw bramble
wet fox
#

bahaha it works i love it

lilac grove
stray field
#

Comes with vim

crisp jay
wet fox
#

theres also an adventure game for vim

raw bramble
lilac grove
stray field
lilac grove
stray field
#

And so is echo

lilac grove
#

idk tbh i can use echo but i made this as fun cmd only

gleaming knoll
crisp jay
stray field
#

We need a !man command

lilac grove
wet fox
#

bruh watching guido present rn and he made all the question askers women! pretty cool feminist

crisp jay
#

How python have integration with C/C++ code?

lilac grove
#

use cython

#

u mean that ?

gleaming knoll
crisp jay
lilac grove
granite wyvern
coarse salmon
#

Best practice is to use it in your projects

#

I tried and gave up since I was too unproductive lol

gleaming knoll
crisp jay
lilac grove
#

it's easy

coarse salmon
#

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

granite wyvern
coarse salmon
#

True

lilac grove
crisp jay
lilac grove
#

or you can start with vs code with vim extension

crisp jay
#

No way

gleaming knoll
crisp jay
#

Making a smart compiler for C would be cool

gleaming knoll
#

what do you mean by "smart compiler"?

#

are the existing compilers stupid?

#

hello fix

#

happy 8 march 🥀

spice hill
#
$ 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...
crisp jay
gleaming knoll
#

oh you just mean like doing it yourself as an experience

#

yeah its a fun task

gleaming knoll
#

ai compilers 😭

raw bramble
golden plank
#

Trying to understand memory management. I now have more questions than answers lol

#

Know of any good resources?

gleaming knoll
#

i dont have resources, but i have a tip : dont think that it is more complicated than it is.

prime sorrel
#

you're not serious are you, AI compilers? 😐

opal gull
#

llms can probably produce correct assembly for simple stuff

#

just dont expect it to be... smart

pallid garden
#

tragedy in slow motion

gleaming knoll
#

ML is useful for heuristics in compilers though
but yeah making the actual compilation process AI driven is insanity

pallid garden
#

good luck certifying a stochastic process

frail scaffold
#

How long does it take for you to forget to write code?

pallid garden
#

6 hours

frail scaffold
#

I havent programmed in a while because of freaking school😭

frail scaffold
pallid garden
#

it certainly feels like 6 hours

tame hinge
frail scaffold
frail scaffold
finite rose
#

Elite skills require daily practice to maintain

pallid garden
#

i feel like i have lost all ability to code in the morning

finite rose
#

Just like an athlete

frail scaffold
#

I will probably take a gap year after high school to develop my programming skills

gleaming knoll
frail scaffold
frail scaffold
pallid garden
#

you cant brute force learning programming

pallid garden
#

trying to program continuously for a year is not going to help

pallid garden
#

you should try to pack in programming after school work

frail scaffold
timid ember
#

What happened to time management

pallid garden
#

it's built up slowly over a long period of time

frail scaffold
timid ember
#

You dont need to learn fulltime

pallid garden
#

join a programming club or something

frail scaffold
pallid garden
#

put in maybe 3-4 hours a week

frail scaffold
pallid garden
frail scaffold
frail scaffold
timid ember
#

💔

pallid garden
#

it's best you dont take things as guaranteed

frail scaffold
frail scaffold
crisp jay
#

Do medicine students have a social life?

timid ember
#

Dont you need a bachelors before you can enter medical school?

frail scaffold
frail scaffold
timid ember
#

Dude you can have hobbies while still studying fulltime

blazing citrus
#

hi everyone

frail scaffold
timid ember
#

You dont need to take a gap year to practice a hobby

crisp jay
timid ember
#

idk

#

depends what bsc you choose and your time management skills

#

yo PLEASE learn effective time management bros💔🙏😭literally the most important thing

timid ember
#

.topic

verbal wedgeBOT
#
**What is your favorite Python package?**

Suggest more topics here!

charred tusk
#

!pypi imsosorry

edgy krakenBOT
#

Sometimes it can be necessary to call upon the ancient arts...

Released on <t:1739593163:D>.

charred tusk
#

Like this server, but in person

pallid garden
#

it's good to have 3-4 hours that is reserved just for programming every week

#

programming skills is built up over time

crisp jay
edgy krakenBOT
#

Official Python bindings for Selenium WebDriver

Released on <t:1771558926:D>.

pallid garden
#

not 1 year of full time cramming

raw bramble
pallid garden
#

yea thats how i got started

#

though i guess the effectiveness differs between people

crisp jay
pallid garden
#

your school?

raw bramble
#

I’ve not met someone my age who can program 😭🙏

charred tusk
#

(Whats your age bracket?)

crisp jay
raw bramble
#

And it’s weird because I do Cybersec

pallid garden
#

the schools here all have some programming related club

crisp jay
pallid garden
#

just pick one of them

#

wdym

timid ember
#

How old r u?

hardy rose
#

if people can hate for no reason i can love for no reason

timid ember
#

Unc

#

jk

#

you can probably find some kind of stem club in your local library

pallid garden
#

if you already graduated then you can just program full time

timid ember
#

They might be slow tho

#

Study and get your certificate equivalency

#

if you dont have a diploma

charred tusk
timid ember
#

Local libraries also have programs for things similar to that (at least where i live)

pallid garden
#

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

silver plover
#

Also, look for Python users groups and meetups

charred tusk
#

Groups

#

Of users

timid ember
#

Irl users

silver plover
#

Meetups are less formal

gleaming knoll
#

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

humble jungle
#

Has anyone heard of obj to ascii project?

pallid garden
#

object to ascii?

humble jungle
pallid garden
#

how does that work?

#

3d ascii?

humble jungle
#

Yeah

#

Well it renders to an ascii buffer

#

Where i think each character is a pixel but I might be wrong

pallid garden
#

a 2d projection of a 3d model, rendered in ascii?

humble jungle
#

Yeah

gleaming knoll
#

everything rendered on a monitor is a 2d projection

cerulean ravine
pallid garden
granite wyvern
gleaming knoll
#

me when the polygon triangulation

humble jungle
pallid garden
#

speaking of ascii art

granite wyvern
#

Aye. I looks very cool.

pallid garden
#
 ┌────────────┐               ┌────────────┐                
 │            ├─┬────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
gleaming knoll
#

and put that into a docstring to make people suffer

granite wyvern
#

Ah that's a better arrow glyph than I've been using.

humble jungle
#

The rendering for that is off

granite wyvern
pallid garden
humble jungle
#

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

spice hill
pallid garden
#

not enough ascii

granite wyvern
#

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 |

gleaming knoll
#

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

silver plover
granite wyvern
whole mango
#

Mola

gleaming knoll
#

i love the internet for that

crisp jay
#

Like how you make letter be so similar to things that arent letters

humble jungle
#

You can make vertices rotate and it looks really cool

#

Just got to know a lil math.

whole mango
#

How does this bot works?

#

@silver plover

silver plover
whole mango
silver plover
#

What bot?

whole mango
#

Python?

viral solar
#

The snake?

shrewd lance
#

Does mypy scream at me if I illiterate over a dict but forgot to put .items()

cerulean ravine
#

though it might not do what you want: it gives you the keys

shrewd lance
#

For k, v in dict:

cerulean ravine
cerulean ravine
shrewd lance
cerulean ravine
shrewd lance
#

Is using freethreading python good for cpu bound tasks?

harsh anchor
#

potentially

gleaming knoll
# shrewd lance Yeah, will mypy scream at me if i forgot .items() ?

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

craggy trench
#

usually for k, v in dict_: means the keys to dict_ is a tuple pair

cerulean ravine
craggy trench
#

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()

gleaming knoll
#

name driven static analysis

craggy trench
#

applying the unwritten conventions of programming

vale wasp
#

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

harsh anchor
#

the typechecker will catch it

vale wasp
harsh anchor
gleaming knoll
#

keys are often strings, which are Iterable[str], so it would do k: str, v: str

vale wasp
# harsh anchor why?

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.

harsh anchor
#

sure. it'll catch some of the cases

cerulean ravine
#
>>> for k, v in {"xy": 1}:
...   print(k, v)
...
x y
vale wasp
runic flower
#

ruff seems fine with it. =/
feels like something that should at least generate an "are you sure"

vale wasp
# harsh anchor what do you mean "it might"

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.

harsh anchor
#

yeah, it catches some of the cases

vale wasp
harsh anchor
#

also: yet another instance of string being iterable causing problems

vale wasp
harsh anchor
gleaming knoll
#

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

vale wasp
harsh anchor
vale wasp
#

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.

jagged belfry
#

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

vale wasp
silver plover
gleaming knoll
jagged belfry
#

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

edgy krakenBOT
#
The Zen of Python (line 5):

Sparse is better than dense.

vale wasp
#

!zen 6

edgy krakenBOT
#
The Zen of Python (line 6):

Readability counts.

vale wasp
#

!zen 4

edgy krakenBOT
#
The Zen of Python (line 4):

Flat is better than nested.

vale wasp
#

!zen

edgy krakenBOT
#
The Zen of Python, by Tim Peters

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!

vale wasp
#

I need to remember it's line 2.

#

.topic

verbal wedgeBOT
#
**Is Python your first programming language? If not, what is it?**

Suggest more topics here!

vale wasp
crisp jay
craggy trench
shrewd lance
#

How do i do multi threading on pyrhon?

vale wasp
jagged belfry
vale wasp
manic flare
vale wasp
jagged belfry
# shrewd lance How do i do multi threading on pyrhon?

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

manic flare
zealous lion
#

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

charred tusk
#

Are we up to 9999 already?

#

I uh... I actually thought this was already a thing

zealous lion
#

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

charred tusk
#

I know I've used...
I think I'm thinking of async with

zealous lion
#

yeah, adding to the collection of async-prefixed things

jagged belfry
zealous lion
#

why?

vale wasp
jagged belfry
#

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

vale wasp
jagged belfry
#

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

zealous lion
jagged belfry
#

!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())

craggy willow
#

don't think i've seen a coroutine with yield in it in a long time

edgy krakenBOT
jagged belfry
#

This is the problem

jagged belfry
zealous lion
#

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

vale wasp
#

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.

jagged belfry
#

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())

edgy krakenBOT
# jagged belfry !e ```py import asyncio async def a(n=1): if n == 4: return await a(n=n...

: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 "/home/main.py", line 12, in <module>
006 |     print(*main())
007 |     ~~~~~^^^^^^^^^
008 |   File "/home/main.py", line 10, in main
009 |     yield from a()
010 | TypeError: cannot 'yield from' a coroutine object in a non-coroutine generator
jagged belfry
#

Interesting.

zealous lion
zealous lion
jagged belfry
shrewd lance
#

Can i string filters in python to geter without forcing them to materialise first?

zealous lion
#

I think that's just cython having different semantics

vale wasp
jagged belfry
vale wasp
#

I'm also not 100% sure there are no security implications here, FWIW.

zealous lion
jagged belfry
#
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

edgy krakenBOT
zealous lion
vale wasp
jagged belfry
#

basically the early version of async there

zealous lion
vale wasp
#

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.)

zealous lion
jagged belfry
vale wasp
edgy krakenBOT
#

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'.```
jagged belfry
#

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

zealous lion
vale wasp
# zealous lion could you elaborate on this?

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.

jagged belfry
#

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)

zealous lion
#

the reference implementation raises an exception that says Did you mean 'async yield from'? for that example

jagged belfry
#

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

vale wasp
#

It seems like async yield from is making something that is already complex even more so.

zealous lion
#

it does do both, it wraps it in a special object like i've said

jagged belfry
#

But how do you know which it should be?

zealous lion
#

you don't need to, python handles it for you

jagged belfry
#

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?

onyx pumice
#

hi i need help, my code in python x app is not working even though it shows the same output as the desired one

zealous lion
#

you await one, you yield from the other

jagged belfry
#

You can yield from futures

zealous lion
#

in old-style coroutines, yeah, but i'm not sure how that applies here

onyx pumice
vale wasp
onyx pumice
jagged belfry
#
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;
}
sand hornet
vale wasp
jagged belfry
#

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

zealous lion
#

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

jagged belfry
#

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()

zealous lion
#

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

vale wasp
#

But would it with the suggested change? And if it doesn't, would it work as expected?

zealous lion
#

without the suggested change you get a SyntaxError for using yield from in an async def

jagged belfry
vale wasp
#

So if you try to yield from a future it would raise a RuntimeError?

jagged belfry
#

Because you are iterating into the future itself and basic python futures have an error check for that

stray field
#

This will let us return a coroutine from a generator then do async yield from await (yield from x())

jagged belfry
#
    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)

zealous lion
jagged belfry
#

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

zealous lion
#

this seems like stuff that will likely be handled by a type checker anyway

vale wasp
jagged belfry
#
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

vale wasp
#

Not everyone uses a type checker.

jagged belfry
#

I think this is a valid test case? It should throw out several values before eventually erroring..

zealous lion
#

practicality beats purity. you could pretty much reject every proposal on the basis that "someone might accidentally write a bug using this"

pallid garden
#

haskell meanwhile:

zealous lion
jagged belfry
#

Yes but did it print anything before that?

#

or just immediately error?

vale wasp
zealous lion
#

oh, there was one <Task pending name='Task-2' coro=<steps() running at /home/peter/develop/cpython/a.py:3>>

jagged belfry
#

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

zealous lion
#

I don't think it's a very big problem if it throws a big error at you right after

jagged belfry
#

The problem is you're not going to get that error: you're going to get a different one, probably a typeerror

vale wasp
#

But right after could be a while. And, as @jagged belfry says, the error is likely to be unhelpful.

jagged belfry
#

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

hallow root
#

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

peak relic
vale wasp
edgy krakenBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

jagged belfry
#
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

hallow root
#

Theme features and such for the store I work on

zealous lion
#

this seems like a toe stub gun, if anything

peak relic
jagged belfry
#

Maybe? But maybe worth addressing in the pep regardless?

#

Sorry, I don't mean to be combatitive

hallow root
#

Something like trello but simple

zealous lion
#

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