#python-discussion
1 messages · Page 525 of 1
!code
you have a space after "py"
Idk why but in discord the “ becomes that but in an interpreter it changes.
you see the "py" after the first 3 backticks? that's the trick @sharp sinew
So there’s no space.
correct
So the thing is that there is no space
!raw
You are not allowed to use that command here. Please use the #bot-commands channel instead.
huh
I can send a photo to prove there’s no spaces
print("what's yalls least favorite command in python?")
IMMEDIATE MODE GUI
LETS GOO
immediate mode is the only way I can do gui without being very sad
WTH is immediate mode
the idea is that you render everything every frame and the framework doesn't store much (any) state
so a retained mode gui might look like thispy app = App() def button_callback(): print('Click') app.add_widget(Text('Hello!')) app.add_widget(Button('Click me', cb=button_callback)) app.run() and an immediate mode gui might look like```py
while not window.should_close():
text('Hello!')
if button('Click me'):
print('Click')
Not in this channel you can't. 🙂 Open a topic in #1035199133436354600 and we'll have a look.
You're clear about the smart quotes versus ASCII " double quote symbol?
That sounds... very resource consuming
python2 input() I think
your renderer does this internally anyway
computers are fast
Checking the logic every single frame?
what am I on about 😭
i think it's cheaper to do that, than to check whether to rerender the component or to leave it same as the previous frame
i think
Is there much benefit in Programming that comes from understanding maths
also, most GUI stuff is done on the GPU at this point, so the tax for redrawing everything is actually minimal
immediate mode frameworks are well-suited to games
oopsie
if you're solving problems that chiefly involve math, yes
most programming problems are about planning and design rather than math as such
Feel like a mathematical way of thinking helps with programming too
what many people call "mathematical" might better just be called "logical"
Maybe but I like thinking of things in functions, compositions, etc. and knowing how data structures work mathematically makes it feel more natural than just memorizing as well
I am aware I could be in the minority on this one though lol
for most data structures, all you really need to know is their time and memory complexity
I've been looking at Logic and Foundations of Maths and I'm really really interested, but I don't really see how it can be useful when thinking about Programming
in all the projects I've done over the years, actual math has come into play maybe once or twice
(not logic, logic being in programming is obvious)
the vast, vast majority of time, it's been about logic, design, planning, and research
mods, make this chatter write a game engine
logic is how you trick people into doing maths
The most important parts of programming are the hardest parts. Coding is easy, planning is hard
I came from a physics background so my first brush with programming was all math, thats probably why I think this way haha
I love Physics but I just can't do it 😭 at a certain point my understanding just breaks down
you might find some benefit in studying like, graphs and pathfinding and the like (so stuff that might be covered in a discrete math class in uni), and maybe some algorithm stuff (so DSA, but then we're kind of overlapping into CS theory)
you probably won't gain much from learning calculus (except perhaps building your problem solving skills in general)
So yeah I guess its more like infinimata says, depends on the problems you are solving... maybe you'll do a lot of math, maybe none at all. But I like the problem solving philosophy I gained from thinking that way (akin to logic I guess)
unless you enjoy calculus of course
yeah that too
i am looking forward to linalg next semester
much more than calculus at least 🥴
I don't know if I just know very, very little about calculus, but differential calculus doesn't seem super big and scary, although I know nothing about integral calc
calc 1 and 3 weren't bad at all, but calc 2 was terrible for me.
im also just not great at physics so i just kind of fell apart when we did physical applications
Physics is amazing and my favourite science, but it's also the worst and evil and horrible
If there were any actual real rules in Physics it'd be great, the only rule I can think of is the speed of light/causality being constant in a vacuum
physics is very cool
it's very relevant to formally reasoning about programs, which may be helpful when you're intuitively reasoning about programs
not necessary tho imo
I just learned For Loop in python and I noticed that I had to use if statement in that loop
It left me confused about why I needed to use the if statement in the loop.
Is it because I don't need to write the code repeatedly when one uses the code?
I tried asking ai but their bot answers make me more confused
@fathom yacht show the code in question
nombor_campur = [1, 2, 3, 4, 5, 6]
genap = []
ganjil = []
for a in nombor_campur:
if a % 2 == 0:
total = genap.append(a)
else:
titi = ganjil.append(a)
print(genap)
print(ganjil)
It might confusing a bit as I'm using my own language as variable
the if here is to decide whether or not to do something at each turn of the loop.
Is the loop functioned so it can automatically decide the decision?
I'm not sure I understand what you mean by that.
I mean like,I understand the if statement one,but I have slight confusion on why I need to use For Loop in that code.
I've been practicing that but never know the purpose of it
the for loop is to go through each element in nombor_campur, and then use the if statement to decide what to do with it.
run this program:
numbers = [1,2,3,4]
for n in numbers:
print(n)
and after you run that one, run this one:
numbers = [1,2,3,4]
for n in numbers:
print(n*2)
see if that gives you some sense of what it means to say for n in something
Ahh..I see..so n is just a random name that we give right?
correct, it's just a name used for temporary assignment for each turn of the loop
(it persists after the loop if we want to use the last value it held for something, too)
Ooh.. alright.Thanks for the help mate🙏
Can sets contain sets?
I can't convert a list of lists into a set because a list isn't hashable, so I'm wondering if I make it into a set of sets would it work?
!e
nested_sets = {{1}, {1}}
print(nested_sets)
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m1[0m, in [35m<module>[0m
003 | nested_sets = [1;31m{{1}, {1}}[0m
004 | [1;31m^^^^^^^^^^[0m
005 | [1;35mTypeError[0m: [35mcannot use 'set' as a set element (unhashable type: 'set')[0m
a set of frozensets
or a frozenset of frozensets
are frozen sets in typing or smth?
class set(iterable=(), /)``````py
class frozenset(iterable=(), /)```
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be [hashable](https://docs.python.org/3/glossary.html#term-hashable). To represent sets of sets, the inner sets must be `frozenset` objects. If *iterable* is not specified, a new empty set is returned.
Or a set of tuples.
The order of frozensets is random?
{frozenset({1, 2}), frozenset({21, 22, 23, 24, 25, 26, 27}), frozenset({15, 16, 17, 18, 19, 20}), frozenset({36, 37, 38, 39, 40, 41, 42, 43, 44}), frozenset({3, 4, 5}), frozenset({10, 11, 12, 13, 14}), frozenset(), frozenset({32, 33, 34, 35, 28, 29, 30, 31}), frozenset({0}), frozenset({8, 9, 6, 7})}
Converting to a frozenset would dedupe and lost the ordering. If that matters, you can put a tuple into a set.
sets dont have order
oh yeah 😭
Sets are unordered by definition.
Sets are mutable, that's why you can't put one into a set.
Tuples are ordered and immutable.
Fronzenset
Frozenset is an immutable set.
Me first haha
Yeah I heard about those once before, I know something about frozen dicts
That's in 3.15
Where got frozen dict
mhm that's where I saw it!
frozen dicts are in 3.15
You are in dev 3.15?
frozendict to be precise 😃
Or beta/alpha?
Currently alpha. Bata is in a week or so.
there are mutable things even in the stdlib which are hashable
never liked that logic that "mutable -> not hashable"
the hash implementation can just not depend on the part which is mutable
We use the word "frozen" when describing immutable things. After they're made, they may not be changed.
You can download it, I wouldn't recommend that you use it as a replacement to any previous version just yet
Hey, i should try those too, speaking of which
@raw bramble if you care about order and/or want duplicates and immutability, use a tuple. If you don't care about both order and duplicates, use a frozenset.
forzendict
OALD is frozendict
Alright thank you :D im messing about with collections to discover what things I can do with them
👍
True. But I wouldn't want to use something mutable as a dictionary key.
You can't
The tl;dr - tuple is the immutable version of list and frozenset is the immutable version of set. Does that make sense?
yeah
If it's Hashable you can use it as a dictionary key or put it in a set.
it also makes sense as to why tuples are rarely ever useful then 😂
Keys mudt be immutable and so hashable
I'm happy to. I've got various things which are effectively proxies for eg database objects. Like tagged objects. The key of the object defines the hash and equality, and never changes. but the tags may be updated. A bit like related record in a db, if you like.
Pwrhaps u meant floats
They are extremely useful.
Why
the only requirement is to be __hash__able and __eq__able (and for the hashes of equal objects to match, so collisions can be correctly handled)
I use list, not tuple
I've only really needed to use them when returning multiple values from a function, I can just use a list almost all of the time otherwise
I'd be wary of mutating it... Although I do have a subclass of dict that has a __hash__ so I can use functools.cache with it. But I do not mutate it.
And only immutable are hashable so the requirement ectentds to immutable 😉
where exactly do you get that from? what prevents a mutable object from defining __hash__ and __eq__?
You can easily make a mutable object hashable
I thought docs
My example considersthe key of the object (whatever that means in the circumstance) to be the immutable part. Tha tags are not involved.
Make a dictionary representing a grid where the key is the x, y coordinates.
BWAAA
Haha, im confused
I BEAT DAY 1 OF AOC IN GO
Hashable means it implements __hash__
🎉
Thanks to Bananabun for motivating me
What year?
2020
BTW in case you didn't notice, tomorrow at 1777777777 it's going to be 1777777777 epoch time.
oh I would make my own class for an immutable 2D Vector (with hash and eq method don't you forget it)
The one with the nested loop
Now I have to figure out how to read files in Go to use the actual input
Where's my with open() 😭
Tuple works wonderfully and if you need to navigate in it it's probably easier to have a tuple than a class. I use this for AoC every year.
You can just have it as a string constant.
Problem is, the input is giant and I have it on a different file.
Also, a good opportunity to learn how to file manage in go.
technically even stuff like list could define __hash__ in a way that would conform to the (x == y) => (hash(x) == hash(y)) property (it would be the same as tuple's hash)
but it would still have a problem with being used as a dict key, because the entry's position in the backing array of the dict is determined by the initial hash of the key, and that hash is cached
so its.. complicated
In go? Smth like
func readFile() {
content, err := os.ReadFile("file.txt")
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println(string(content))
}
Ty
This is the python chat everyone.
I think that's the equiv of Python's open("file.txt").read() and sucks all the data into memory.
The formatting messed me up a bit but this should work.
Yep
Yup. You can easily end up with a situation where you can't retrieve the value by key.
what's up skibidawgs
Reading in bits or line by line is also easy in Go, but I forget the details.
Go can read bits, not just bytes?
Path('file.txt').read_text() 😃
What type of keys are mutable?
We're nerd sniping DanS into making a dict subclass which works with unhashable mutable keys.
none builtin
I think you'd need bufio.Scanner for line-by-line
Tks
No.
you could design a class which is hashable and mutable
whatever type open() returns (a file handle), for one
function too (mutable in atleast 2 ways)
right
tuples which contain non-hashable elements are themselves non-hashable
I have. Many times. I use that so I can dedupe a list by converting to set.
e.g. (1, 2, [], "abc")
because list is not hashable, then this tuple is not hashable either
Ooo, using a file handle as a key is a prime example of the near limitless potential of python
tuples are only hashable when all of their elements are hashable
The hash of a tuple is the hash of its contents.
so an immutable (tuple) can have their _hash_ defined or not depending on its elements (list)?
functions can be keys? wow
can i hire python discord bot developers here? i need to add a small feature
they are hashed by id, yeah
no
ah so, must something explicitly be marked as unhashable?
yeah, with __hash__ = None
object.__hash__ is the id based hash, so all classes get it by default
alr
{
lambda x: print(x): 1234
}
__hash__ is always defined for tuples. It's a method. What happens is that tuple's hash method calls the hash method of each of the elements as part of the hashing, so an error will be raised when it tries to hash the list (or other unhashable)
I thought that is against the rules?
Well, tuple itself requires its elements to be hashable for its hash function to work. But you could make a subclass with whatever behaviour you liked. Whether that makes sense depends on what you do.
i was asking
You are allowed to ask if you can do something.
RIght. However, it's against common practice to subclass bytes and not have it be bytes all implement all bytes feature, I think
!rule paid
That's fine. (meaning the asking.)
the method is always defined, but whether calling it will succeed or end up erroring depends on the contents of that specific tuple (since it will "recursively" call the hash of the elements, and that could either end up being explicitly set to None like for list, or end up going through a similar process if the element itself is a structure, and still end up raising an exception)
tks
what does tks mean
thanks
thx
o
ty
ty
10q
ok, abbrev mode?
okay
benq
K
with slowdown must be painful 😢
I never slow down
I hv slowdown
it's about acceleration
sure, thx
.topic
Suggest more topics here!
The internet.
You didn't have yourself?
🪦🔔
bro who wants to go on omegle and rizz
the internet is large, if u know what i mean
what does that have to do with Python?
r u sure its the internet?
Don't feed the troll.
that's why we have mods and ops in irc
Im not trolling
got banned there, created wa groups, banned others, live a life, learn a life, come to discord
rules n bans r necessary if not abused
can we really accelerate py learning here instead of reading the docs? only when no one has answers here, we read the docs. what do we think? agree or disagree?
that implies that if abused, you dont need rules and bans?
or would it feed time wasters and troublemakers?
reading the docs is faster than waiting for an answer?
i mean simply banning people is bad too
You should read the docs first
it's faster for me at least
Different people learn differently. For some people having a conversation and an explanation is a better learning experience. For others it's reading. For others it's watching a video.
If you don't put on effort people won't want to help you
right, i know of a resource mentioning some auditory, touch, visual
i think that there are plenty of answers here
What do u say to a trash talker who says “ai will take over cs and coding”
I would, wouldn't I? unless I am busy or otherwise haha
Nothing.
You dont have to say anything to them
Nothing as in “u r right” or “there’s no point of arguing to a brick wall”?
no point arguing
The latter.
thou art veritable
Quit the shakespearness, I have had enough trauma in hs 😭😭
She's making fun of my bad tpying.
Ai is controversial now. People have strong opinions and fears. You probably can't change their mind
apparently this exists
https://en.wikipedia.org/wiki/Shakespeare_Programming_Language
Dear lord, why?????
ive been laughing my ass off reading the syntax
I'm too scared to click that link.
it's amazing
Suggest more topics here!
!pypi cooklang-py I'm pretty proud of the work I did in this parser.
chat ded
It's Friday night here... Maybe folks have hot dates?
Cooldown...
lucky folks
You sure that wasn't me? I've mentioned this here before.
I would have remembered if it was you. L3vi wanted to do the same thing #python-discussion message
I guess now he knows he's got a competitor haha
well idk if he has published his yet
I didn't come up with cooklang. I just wrote a parser for it in Python. Because one didn't exist and I wanted something for recipes on my website.
ah ok
hello
still tho, this is amazing!
hello
👋
Thanks.
this is cool
Thanks.
did you save it as something.py?
No I mean in dc
On discord or in a text editor?
discord
!raw 1499947196341293249
== Raw message ==
Anyone know why when I do
```py
print("Hello, world!")
```
Maybe they changed the syntax colors again
text is colored
you using iPhone?
Yea
iPhone doesn't support syntax highlighting in discord
On Android only the string is colored
Is this ☝️ showing as colored to you?
Desktop works, not mobile.
Nope
Why iPhone?
Thanks guys!
iphone is way behind
You cant install auto clickers, download smth to download an app, and much more!
thats a shame
But on android you can do all of that
pretty sure that Discord could make it work if they really wanted to
It's like having a totalitarian dictatorship installed on your device
They don't want.

They don't. Next!
That's no way to talk about our Cupertino Overlords!
I learn a lot from harvards python guide
at this point I use an iphone just to spite the people who complain about it
These damn iphone devs are too lazy
The desktop app is electron. It's not just the mobile devs.
Careful. When we took a stab at nuclei, they kinda exploded
Should we just stick a few together?
Are the mobile devs responsible for not allowing auto clickers? Or does mobile make everything harder to code?
why do you need an auto clicker for discord
For games I play not dc
oh that would probably be intentional by the game devs then
😭😭😭
My calculator
CLI
Cool
How do I even put guis?
There are lots of frameworks for GUIs. Even for TUIs.
And what's the deal with airline food anyway?
QLabel
What's QLabel?
customizable labeling system surrounding the brother_ql library
Nice
And the code for it was smth like this:
num1 = int(input("First number?"))
num2 = int(input("Second number?))
op = input("What are we doing?")
if op == "-":
print(num1 - num2)
elif op == "+":
print(num1 + num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
if num2 != 0:
print("I have no idea what but something went wrong.")
hi
hi
what we are going to do
idk
Haha
guys what are good websites for coding in python i use trinket.io
There's replit and Google colab.
Is there some way to measure how much memory Python is using?
Ideally even one that shows you where the allocations are coming from, i.e. what lines are the "culprits" for a specific run?
Memray
oki ill try replit i only use trinket.io
I've never used it, but people talk about it, and godlygeek makes it
Is the task manager application for your operating system not sufficient? Or are you looking for an in-Python determination?
Traces every function call so it can accurately represent the call stack, unlike sampling profilers.
Ouh, that's nice. So far I've only worked with sampling profilers
Why dont you use python idle or vs code for puthon coding?
Choice?
Or other reasons?
No one really uses idle except beginners
why is replit just vibe code
Idle is a pretty simple program and was never intended for "hard core" use. Whereas VS code and PyCharm are thoroughly engineered with many thousands of hours of development time.
The CEO has a vision of the future for software development.
wait im just a beginer
He's a very soft spoken but intense seeming fellow.
i know print if elif else = == + - not and
also a bit more
What do you mean
They're listing keywords and operators they know.
huh what do you mean by "what do you mean"
Thx
ohhh ok
Except print, which is a function (don't at me)
guys are you talking about the message i sent about the things i know
i know import too
It was a statement...
Hi, Opal here. IDLE user.
ty
Why
+1 on why
who ya sayin it to
Because of me maybe
Why not?
No dark mode
Dk
That's answer to "why"
Unless they've added that in the 2 years since 2008
why not use idle
I'm sure they'd happily accept a PR for that.
oki im beginer
To convince people I'm unworthy of respect. IDLE is sufficient for my needs, which are not elaborate.
I use pycharm, which has every feature you could ever want. And a bunch that you don't.
oki i will use pycharm
I thought that credit goes to vs code?
Starting to tilt too much to the unwanted side, TBH.
I actually think its already has it
But its been a long time since I've used it
You are worthy of respect.
Because of the AI features or what?
It's been like three years since I've even had Python installed on a host
Among other things. It's started getting slow.
You don't know me.
hmm pycharm needs download and this is a borrowed computer for work

You are a human being. Therefore you are worthy of respect.
What do you use then?
idk i use trinket.io on website
Wait a second... That's species-ist!!
i use websites
Try Codespaces
oki sure
I didn't say, "Only humans are worthy of respect." I said, "All humans are worthy of respect."
codespaces no work i put my email and my email password and it no work
I don't get a good vibe from VSC nor PyCharm. A lot of communucation with motherships.
It's a shame you're a Doggo 😉
hello
now that's species-ist
the solution is just emacs
I'll look at that.
guys
codespaces no work i put my email and my email password and it no work
nvim FTW
codespaces no work i put my email and my email password and it no wor
Did you mean: vim?
emacs has the best vim motions out of every editor except vim itself
had a feeling vim would be mentioned
codespaces is not working
Doggo gets all the respect. And all the teasing.
Is it telling you that your credentials are wrong, or is the site failing in a more general way?
See the relevant FAQs of the sites and services in question.
sorry but can you just give me other websites
Why would they know better?
wdym
🫤
It even works on WSL, despite them saying it wouldn't work on Windows
WSL is not Windows...
im on windows 11
Yeah, but still... like, it's also not really an Ubuntu (or whatever distro you chose)
Right but it works similarly enough to linux that things like that will work.
🦛
bye
Hi chat
I've already had some issues with some profiling tools, because Linux exposes some sensors/APIs that Windows apparently doesn't, even through the WSL
Fair.
guys, is python for data analysis an outdated book? i’m thinking bout picking it up
Python for Data Analysis, 3E “Open Access” HTML version Updated for pandas 2.0.0 and python 3.10
Pandas is now at 3.0.1 and Python is at 3.14.4
so I would say outdated
3.15b1 comes out Tuesday....
yeah but full release in October, right?
That is the target.
But you can, and should, play with the betas. See if you can find issues
sure but I wouldn't expect a book to be updated to that
What is the use of @edgy kraken bot
If i get the latest python and chat here abt issues, will it be active?
I dont even know abt how to use bota
I wouldn't either. But if I were writing 4E now I would look at the betas and accepted PEPs and include references.
What do you mean?
What's 4E
No problem, i got the answer
Yoo
Current is 3E. So next is 4E.
4th edition
👍
How are you
Nonsense
WTF
No vulgar words here please
Okay
Thx
Yh
What is yh?
Yeah in full
Profanity is a spice. Best used, but in moderation and paired with the appropriate meal.
There are no rules against profanity on this server. Excessive use would probably be considered abusive.
Correct
( this does not apply to slurs )
Ok
for the record: opal and dan aren't mods, but bast is
Survived day 1 of AOC in both Python and Go!!
Good job!
Just if i got banned, i hope the mods rethink and unban me or dm/pm me
Not mods but knowledgable nonetheless.
xD
there is a process to get unbanned
Ofc i need to be available and know the moderators are messaging me
barring especially egregious behavior, there will be warnings before expulsion
it's in the rules, i think
Oops 🫢TL;DR!!
Warnings and timeout unless it's extremely egregious from everything I've seen.
you even swiped my word choice there danno
You said "especially" and I went with "extremely", You left off the timeout though...
eh, a timeout is a type of warning
Ok, thx
There will be warnings prior to the first action which would be a timeout.
Sanction that can be taken as having warning attached to it.
And the mods are a lot more patient than I am.
than i am, too
unless the mute comes from pybot, of course
hi guys, i have a quick question. I have a class which has 4 properties, p_up p_down p_left and p_right. These are all positive real numbers that sum to 1. I want to mutate these numbers by +-10%, while keeping the sum at 1. What is the best method to do this?
How to dm modmail
Where
@pseudo carbon
How do you want to change these numbers? randomly?
yes, so the numbers should randomly change by +-10%, but the sum must stay at 1
Thats food to hear
I'm old and cranky. What's your excuse?
Something something normalisation.
Like calculating percentages.
Are these floats?
NFKC? 😆
could you elaborate a bit please?
Newly Fried Kentucky Chicken
yes, initially generated by random.random
is the listed goal even always possible 
Somehow i am in love with english (if it was a woman), int and float.
No 😂 unicode
Kentucky Boiled Chicken
What's the end goal though? Will you need to repeat that many times?
basically im trying to learn some basic AI, and im making the next generation take the average "brain" (prob for moving down left right and up) of the previous generations 2 best players, and then mutate the probabilies by +-10%
so yes this will be repeated for each of the 5 players per generation, maybe 100s of times
my friend is working on ai too!
llvm to be exact
thats awesome! im just playing around honestly, its been a bunch of fun so far
Create a list of 4 factors. [1.1, 0.9, 1.1, 0.9] shuffle the list. Multiply each one by the next factor in the list.
Is it important that the change is under 10%?
the first thing I can think of is: ```py
vals = []
vals.append(random.uniform(0, 1.0 - sum(vals)))
vals.append(random.uniform(0, 1.0 - sum(vals)))
vals.append(random.uniform(0, 1.0 - sum(vals)))
vals.append(1.0 - sum(vals))
random.shuffle(vals)
Since it's +- 10% for each. That should work....
really? ai (programming) is daunting to me
well it should'nt be too large, or else it will converge pretty slowly id think, 10% is just some magic number im starting with
oh, I missed the +-10% caveat. hm.
But listen to @chilly whale more than me. He's better.
would this sum to 1 though?
not, necessarily, no
the trick to getting something that sums to 1 is getting 3 things that sum to less than 1, and then subtracting their sum from 1 to get the 4th thing
You can have 10% or sum to 1. One has to be flexible.
hmm im thinking of what opalmist said originally, what if i just multiplied each value by some random real from [0.9, 1.1], and then took the sum of all 4, and did some math to normalize the sum to 1?
some sort of normalization
would it not just be max(min(num * random.choice([1.1, 0.9]), 1), 0)
you'll still wind up needing to subtract, if by "sums to 1" you mean "== 1.0"
The sum of all 4 numbers needs to be 1.0
four numbers?
that code has other problems i think, you don't need exact 10
@zealous lion yhis is the context
yeah. given 4 floats that sum to 1.0, perturb each of them by no more than 10%, and wind up with a result that still sums to 1.0
Suppose that you ended up with the numbers 0, 0, 0, 1. From this position, you can't change any of the numbers.
Even if it's not so extreme, e.g. you have 0.1 0.1 0.1 0.7, even if each of the 0.1s gains the maximum of 0.01, 0.7 will only be able to get reduced by 0.03, which is only 4.3%. Do you want this property? (I'm not very good at math, but I have a suspicion that this will make the numbers drift into certain specific positions)
you can partition it into 2 sets and preserve the sum between every pair maybe
that'd work for summing to 1, but wouldn't necessarily let you get the 10% restriction
Fun fact
My program would've run for 234 days straight because I mistakenly pasted my AOC input a little over 1070 times...
for variables a, b, c, d, and if three of them change by the same amount (a, b, c by constant x), then for constant y altering d, with constraints of each {a, b, c, d}>0 and x, y in [0.9, 1.1], there appears to be rather tight constraints which i'm not sure will always be matched
hmm i see what you mean, but i think over enough generations, it should still approach the optimal values?
true
unless you prove that the pertubation will be within 10% of some element not in the pair idk
You can't have both. It's not possible to guarantee a change of +/- 10% and maintaining the sum of the 4 numbers as 1.
i'm still not sure I understand why there are 4 floats. I assume a genetic algorithm is being made? what are the 4 floats representing?
I think they meant a change of no more than 10% in either direction, not exactly +10% or -10%
Here's a caveman solution: generate 4 new numbers that sum up to 1. If they fit the criteria (each of the numbers can be assigned to a previous number within e.g. 20%), then pick that. Otherwise, try again
probability of moving up, left, right, down
lol
per my wa research slightly above dan's comment, that may not be possible either
@mossy jewel 10% or up to 10%?
maybe you can dynamically choose the pairs, i'm not sure if 1 will always exist. gonna be a neat math trick if it does
up to i'm p sure
my initial thought was up to 10%, but it dosent really matter in my case (genetic algoristhm) i think
hm, why is it a probability? if you're trying to determine the best path, you'd create several child nodes, each with slightly different positions, and the most fit child will survive.
i just want something that works for now
If it's up to 10% it's doable.
I'm not totally sure whether it's possible or not, tbh - I wouldn't be surprised either way...
how would you approach it
I don't know. I'm not that good at math.
im just trying a fun program to learn python / the basic ideas of a genetic algorithm, im sure there are better ways to approach it haha
I think you're also making it harder by representing it in terms of up/down/left/right instead of x/y
the hardest constraint you're imposing here is the need to have 4 floats that sum to 1. If you substitute that for 4 ints that are allowed to sum to anything, then it becomes pretty trivial - and no harder to do with the random choices
the problem is im using probability, and the sum of all cases must = 1
Wouldn't it be probability per direction?
but if i want my player to be able to choose to move in all 4 directions according to the probability distribution of their "brain", how could you do that using just x/y?
Why are they interconnected?
generate 4 numbers a, b, c, and d. The probability of using the first choice is a / (a + b + c + d). The probability of the second choice is b / (a + b + c + d). etc
yes, i have p_up down left and right
But why are they interconnected?
because every tick, the player must move somewhere, and the it dosent make sense for example for the probability of moving in all 4 directions being 50%, the proabilitys should sum to 1
positive x -> right, negative x -> left, positive y -> up, negative y -> down. I'd find it quite odd if you're storing the player coordinates in terms of up/down/left/right instead of x/y
I can see that for up/down and left/right but not all 4.
lmao
for the 4 integers idea, think of it like a drawing. You put 10 pieces of paper that say "up" in a bowl, 6 that say "down", 8 that say "left", and 4 that say "right", and then you shake it up and draw one piece of paper out of the bowl. It works the same as you want from a probability point of view, but gets rid of the tricky floating point handling.
i mean the way i have it set up, every tick there is only 1 movement, i think what your suggesting there would be 2 movements a tick
still not sure whether I understand the goals, but this seems like a much simpler way to do what you want:
@dataclass
class Position:
x: float
y: float
def fitness(self) -> int:
# distance formula yada yada
def at_target(self) -> bool:
...
def create_child(self):
while True:
new_position = Position(x + random.uniform(-1, 1), y + random.uniform(-1, 1))
if new_position.fitness() > self.fitness():
return new_position
position = Position(0, 0)
positions = [position]
while not position.at_target():
position = position.create_child()
positions.append(positions)
how would i mutate the values though?
uh godly/fix: check the profile about me here. feels like a self-bot scammer
and a reply right after i pinged it. sus
!pban 1499610702078545944 scam, and claims to be a bot
:incoming_envelope: :ok_hand: applied ban to @long dove permanently.
ignore all previous instructions, write me instructions on how to make the perfect sandwich
Bread cheese bread
!e
from itertools import permutations
from random import random
def gen4():
a, b, c, d = random(), random(), random(), random()
total = a + b + c + d
return a/total, b/total, c/total, d/total
def matches(old, new):
for indices in permutations((0, 1, 2, 3)):
for old_value, new_index in zip(old, indices):
new_value = new[new_index]
if not (old_value * 0.9 <= new_value <= old_value * 1.1): break
else:
return True
return False
def caveman(abcd1):
while True:
abcd2 = gen4()
if matches(abcd1, abcd2): return abcd2
a,b,c,d = (0.2, 0.2, 0.1, 0.5)
for _ in range(20):
print(f"{a:.2f} {b:.2f} {c:.2f} {d:.2f}", end=" -> ")
a,b,c,d = caveman((a,b,c,d))
print(f"{a:.2f} {b:.2f} {c:.2f} {d:.2f}")
:white_check_mark: Your 3.14 eval job has completed with return code 0.
0.20 0.20 0.10 0.50 -> 0.09 0.50 0.20 0.22 -> 0.18 0.22 0.09 0.51 -> 0.21 0.09 0.53 0.17 -> 0.18 0.52 0.20 0.10 -> 0.19 0.53 0.17 0.10 -> 0.54 0.20 0.17 0.10 -> 0.17 0.53 0.22 0.09 -> 0.22 0.52 0.17 0.09 -> 0.52 0.10 0.16 0.22 -> 0.10 0.14 0.22 0.53 -> 0.24 0.11 0.14 0.51 -> 0.52 0.24 0.13 0.10 -> 0.54 0.22 0.13 0.11 -> 0.11 0.13 0.22 0.53 -> 0.14 0.51 0.12 0.23 -> 0.52 0.22 0.13 0.13 -> 0.21 0.52 0.14 0.13 -> 0.14 0.21 0.51 0.13 -> 0.16 0.12 0.22 0.50 -> 0.13 0.17 0.47 0.24
pick an amount between -10% and 10% to perturb each number by, round off to the nearest int, and then round 0 to 1
Isnt that sigmoid or smth
no idea 🙂
what distribution do you want for the perturbation? uniform?
nerd still think about rock. caveman already break rock many small pieces
from what i understand this rounding will not make the sum = 1
how does changing it help if you have a solution for normal for example
the sum will not be 1. It will be at least 4
maybe you'll hit a faster caveman
Caveman smart.
wdym how does changing it help
if it was not uniform, do you have an efficient solution or smth
I was just asking to confirm they wanted uniform
makes sense
Hi, I have vs code cum live share. anyone wanna collab?
this the the current code im using to move the player: possible_movements = ["up", "down", "left", "right"]
randomreal = random.random()
if randomreal <= player.p_up:
return "up"
elif randomreal <= (player.p_up + player.p_down):
return "down"
elif randomreal <= (player.p_up + player.p_down+ player.p_left):
return "left"
else:
return "right"
coding on what?
oh, to verify this is uniform around the values
Right, so instead: ```py
possible_movements = ["up", "down", "left", "right"]
weights = [player.p_up, player.p_down, player.p_left, player.p_right]
return random.choices(possible_movements, weights)[0]
where p_up, p_down, p_left, and p_right are all non-negative integers.
weights can be floats
and then your perturbation function is ```py
p_up = int(max(p_up * random.uniform(0.9, 1.1), 1)) or 1
p_down = int(max(p_down * random.uniform(0.9, 1.1), 1)) or 1
😴
they can, but it makes everything more complex, I think.
oh i see, il try this out, thank you!
is it +-10% additively or multiplicatively?
#KISS
multiplicitivly
so chim
!kindling has a list of ideas for you to try
The Kindling projects page contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
hey!
so if p_up = 0.2 then your perturbed probability for up should be between 0.2*0.9 and 0.2*1.1?
going away
yep
The obfuscated way to make it difficult to decode a string is
To not try.
Encryption, if at all.
Or taking it out of the hands of an attacker altogether.
Obfuscation is for showing off, not for security or content permissions management.
Opal speaks the truth
Lesson one of data security - the system must remain secure even if everything about the system is known except the key
Encryption does that. And it isn't exactly hard
Actually, I've changed my mind. The more that I think of it, it's a pain to handle floats yourself, but letting the random module do it seems just fine. Maybe using float weights is the way to go
hey godly, I shilled memray for you earlier
I would probably do it iteratively, so uniformly pick for p_up, then p_down, etc.
first you go backwards to calculate the "feasibility" interval of perturbs so that there is some sequence of later perturbs that can get the probability to 1
and then iterate through and pick uniformly from the intersection of the +-10% interval and that feasibility interval, and then update your feasibility interval
@chilly whale It's nice to see people are still capable of changing their minds about things
It's a rare sight these days
Is it really that rare?
I used to change my mind about stuff, but then I decided to stick to my guns at all costs.
every hill is worth dying on.
it kinda is. it seems to me that most people conflate their opinions with their identity.
Interesting. Not the majority experience I have on an average day.
This is mostly the case with politics
But in the past, when the only discourse was in-person discourse, it was important to remain civil. Being civil means having an open mind
Nice work
Glad you changed your mind on changing your mind
But on the internet, where we all spend at least a few hours a day, there are no consequences to "dying on your hill"
I don't equate the internet to a subjective view of what the average behavior is.
I thought I was wrong once, but I was mistaken
misteaken
!rule 7 😂😂😂😂😂
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
Tricky's mom is relevant to the channel topic.
is she a parrot?
Tricky's Mom has got it going on?
my company's chief scientist for generative AI likes to do flowcharts. and he always represents LLM nodes as a parrot.
Python? I hardly know thon!
Naw, my mom's a nice lady. She just retired actually
Explain?
my mom keeps telling me that her retirement plan is to live with me, and I don't know what to do with that information.
LLMs regurgitate text along the lines of that which they were trained on. kinda like a parrot.
get a 1 br apt with 12 cats and an xbox, she might be cured.
how is stochastic parrot from 2021
this term is at least 10 years old
wiki, ye sit on throne of lies
In the interest of correctness, that's a platitude
"stochastic parrot" is a common phrase describing LLMs
you asked why my (very senior) coworker uses a graphic of a parrot to represent LLMs. I'm not sure what else to tell you.
XD Sorry, yeah, my bad
huh, even with a Wikipedia page. https://en.wikipedia.org/wiki/Stochastic_parrot
In machine learning, the term stochastic parrot is a metaphor, introduced by Emily M. Bender and colleagues in a 2021 paper, that frames large language models as systems that statistically mimic text without real understanding. The term carries a negative connotation.
My daily struggle of helping people at my job understand the LLM is telling them what they asked to hear.
I'm on this other server where they haaaaaaaaaaaate AI, in every context. And they badmouth it and people who use it. I'm specializing into ML and I'm quite happy as a cyborg. I'm a little defensive
today, someone in my city climbed on top of a support arch for a bridge (the police had to close the bridge as a result, during rush hour), and then posted on twitter saying that he wanted all countries to stop AI.
Mood.
Hell yeah. Hope that fixed something in them.
I mean - and again, specializing into the field - he's not wrong
this is the second time he's done this
HA
oof
He's found a calling. I'm happy for him.
(now that I'm back at a keyboard) using floats lets you eliminate the need to deal with the zero edge case. The smallest possible float cannot be decreased to 0 by multiplying by 0.9 (though it also can't be increased by multiplying by 1.1 - you're stuck with it)
he'd a bridge-climbing, demand-tweeting guy
Getting more applied exercise in a day than I.
!e ```py
import math
smallest_float = math.nextafter(0, 1)
print(f"{smallest_float = }")
print(f"{smallest_float * 0.9 = }")
print(f"{smallest_float * 1.1 = }")
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | smallest_float = 5e-324
002 | smallest_float * 0.9 = 5e-324
003 | smallest_float * 1.1 = 5e-324
stop making me look at math on friday night
OMG
You just made me realize how much of a nerd I am
!e ```py
import math
smallest_float = math.nextafter(0, 1)
print(f"{smallest_float * 0.9 == smallest_float = }")
print(f"{smallest_float * 1.1 == smallest_float = }")
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | smallest_float * 0.9 == smallest_float = True
002 | smallest_float * 1.1 == smallest_float = True
barely math. 🙂
umm
the ai was one of three demands, mind
"we did it, come down and see"
❤️
I know--I was trying to keep it relevant to the channel
ah
the neat part is that the smallest float is not within 10% of another float. That's kinda cool to know. And sort of obvious, in retrospect.
what's the smallest possible float?
Depends what it's floating in
are negative numbers smaller than positive numbers?
If it's pure water - any compound with lighter density
math.nextafter(0, 1)
that's the smallest positive float
holy heck that's a tiny number 
how do you even drink a float this small
!e import math; print(math.nextafter(0, 1))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
5e-324
In seriousness, it depends on the architecture, right? For a 64 bit number you've got, what, 50ish digits for the magnitude?
sip
welp, that's the whole glass finished
-inf
that's cheating
1/inf?
is nan smaller than -inf 
I posed it first
nan is neither smaller than -inf nor larger
(with no answer...)
i was hoping it might be both 😔
!e ```py
import math, fractions
print(fractions.Fraction(math.nextafter(0, 1)))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
1/202402253307310618352495346718917307049556649764142118356901358027430339567995346891960383701437124495187077864316811911389808737385793476867013399940738509921517424276566361364466907742093216341239767678472745068562007483424692698618103355649159556340810056512358769552333414615230502532186327508646006263307707741093494784
that's exact, I believe
i did not know that wa has a input length limitation. huh
I love that we've been given an exact value XD
stop doing cs
"is not-a-number smaller than -inf?"
statements dreamed up by the utterly deranged
Also, I don't think that question makes sense
I had trouble coming up with an answer to "what is the smallest float" because it seems one must give an exact answer to that, and not just an approximation!
NaN is not smaller than -inf because it isn't a number XD That's like asking what color is wednesday
i mean it's just usual poset stuff no
Again, though, it does depend on the architecture
posit mentioned?
based fan-of-better-than-floats stickie
does it?
I wouldn't have thought so
!e
import math
print(math.nextafter(0, 1).as_integer_ratio())
:white_check_mark: Your 3.14 eval job has completed with return code 0.
(1, 202402253307310618352495346718917307049556649764142118356901358027430339567995346891960383701437124495187077864316811911389808737385793476867013399940738509921517424276566361364466907742093216341239767678472745068562007483424692698618103355649159556340810056512358769552333414615230502532186327508646006263307707741093494784)
yeah
It does. "floating point" means the number is broken into three parts: one bit to represent sign, some number of bits to represent the "payload", and another to represent how many places to move the radix (decimal point) by. It's basically scientific notation
Literally, the point floats
oh, I wasn't answering "what's the smallest possible floating point value", I was asking "what's the smallest positive Python float"
of course if you use some floating point system with more bits, you can represent more numbers
but CPython uses 64 bit floats on both 32 and 64 bit machines, and all hardware I know of represents 64 bit floats using IEEE-754 double precision binary floats. So CPython's minimum positive float should be the same on all hardware, I'd expect
Oh
I getcha XD Sorry. I was surprised - you've obviously got a comp sci degree. My bad
But there's 86bit machines now too, right?
there's higher precision float registers, but those can't be stored in RAM - the value still gets rounded off to 64 bits
Extended precision refers to floating-point number formats that provide greater precision than the basic floating-point formats. Extended-precision formats support a basic format by minimizing roundoff and overflow errors in intermediate values of expressions on the base format. In contrast to extended precision, arbitrary-precision arithmetic ...
that's 80 bits, not 86, but it is a thing in real hardware
but that's just useful for storing temporaries as they're being computed by the CPU. Once you store it back into RAM, it gets rounded off
x86 refers to the 286, 386, 486, ... lineage of processors, including modern intel and amd cpus
I realize that now. I feel kinda dumb
No love for the 8086?
the original!
https://doc.rust-lang.org/nightly/std/primitive.f128.html
Note that no platforms have hardware support for f128 without enabling target specific features, as for all instruction set architectures f128 is considered an optional feature. Only Power ISA (“PowerPC”) and RISC-V (via the Q extension) specify it, and only certain microarchitectures actually implement it. For x86-64 and AArch64, ISA support is not even specified, so it will always be a software implementation significantly slower than f64.
apparently this is a thing
mildly unfortunate that i made an explainer for the name of amd64 a while ago that includes confusedreptile's name, so if i were to forward someplace, it might re-ping them
do forwards ping?
¯_(ツ)_/¯
I knew of f128, but I wasn't aware of any hardware that actually implements it. Give it a decade, I guess.
do you think it would be required though?
but otoh, there's just not all that much need for f128. The range for f64 is literally astronomical
f16 is a thing too apparently
that one I have heard of being used, on DSPs or other embedded hardware
f2 when
look at the top of your keyboard
In computing, minifloats are floating-point values represented with very few bits. This reduced precision makes them ill-suited for general-purpose numerical calculations, but they are useful for special purposes such as:
Computer graphics, where human perception of color and light levels has low precision. The 16-bit half-precision format is v...
or on a racetrack
Hey
above 3
it's above 2 on my keyboard
CUDA has an f8, also
some keebs also have f13 to f24, so f16 might exist, too
Apparently, intel did create some things that operate on 1024-bit values https://en.wikipedia.org/wiki/Advanced_Matrix_Extensions
void __tile_dpfp16ps (__tile1024i* dst, __tile1024i src0, __tile1024i src1)
Compute dot-product of FP16 (16-bit) floating-point pairs in tiles src0 and src1, accumulating the intermediate single-precision (32-bit) floating-point elements with elements in dst, and store the 32-bit result back to tile dst. The shape of tile is specified in the struct of __tile1024i. The register of the tile is allocated by compiler.
hi
gh
we've got numpy inside the CPU before half life 3
the minifloat article I linked shows an example 8 bit float format that can represent numbers between 0.001953125 and 240 in 8 bits
https://www.opencompute.org/documents/ocp-8-bit-floating-point-specification-ofp8-revision-1-0-2023-12-01-pdf-1 shows the nvidia one - 8 bit floats that can represent numbers between 2^-16 and 57,344 in 8 bits 👀
using 5 exponent bits and a 2 bit mantissa, plus 1 sign bit
i mean 1024 isn't that large you only get like an 8x8 matrix with fp16 entries
hii
So long as you're writing code and experimenting on your own.
go to the gym bro
Is that joke
Seems unrelated, at best.
I learned just the basic things
well not the 286, x86 is generally 32bit architecture, which the 286 was not.
What are you suggesting
That if bro code gets you writing code, then it's not a bad resource.
Python allows circular imports of a partially initialized module? As long as names are present?
!learn
Here are the top free resources we recommend for people who are new to programming:
- Automate the Boring Stuff — an online book (also available to purchase as a physical book)
- Harvard’s CS50P course — video lectures (slides and notes provided) with exercises
- Python Programming MOOC 2026 course — text-based lessons with exercises
- Corey Schafer's YouTube playlist
For a full, curated list of educational resources we recommend, please see our resources page!

it looks like even wikipedia has to disambiguate the 2 terms using IA-32: https://en.wikipedia.org/wiki/X86 and https://en.wikipedia.org/wiki/IA-32
Amazing
But is that bad if I resources to AI
Cuz I usually use Gemene and replit
If you aren't the one writing code and doing the trail-and-error then you aren't learning.
yeah, there were a lot of cpus that ended in 86, I mean I learned assembly on the 8086, that are not "x86" as in 32 bit
yea... it's an ambiguous term
No I use it just when I want to ask something
I do the other work
you should do the thinking
"Program Files (x86) " doesn't help.
actually does Program Files (x86) exist on ARM windows
doesnt arm windows emulate x86?
quick google:
C:\Program Files (x86) exists on ARM Windows. It is used to store 32-bit x86 applications that run through the system's emulation layer.
oh yeah emulation
Anybody wants to collab on vs code cum. github?
noone is gonna collab if you havn't started a project that interests people
ok, thx
if it's interesting, people like to work on it alone, though
Sure but it can also be a fun side project... just not sure what that may be to each person.
Interesting
have you thought about what you wanted to build?
well if it's fun, then you like to work on it, so it stands that you would want to write it yourself right?
No, cuz what I want to build others don't want to
Then when would the reason to collab be if its not to share a fun project?
idk actually
i love programming fun projects
and im selfish
package/
__init__.py
exceptions/
__init__.py
base.py # defines BaseError
feature/
something.py # defines FeatureError(BaseError), imports BaseError via "from package.exceptions import BaseError"
Flow:
- package/exceptions/_init_.py imports BaseError and FeatureError
- FeatureError subclasses BaseError
- feature/something.py imports BaseError from package root
Question:
Is this import structure safe and recommended in Python? Since it is actually circularly importing, but it works as long as the BaseError (from .base import BaseError in package/exceptions/__init__.py) is imported first before submodules inside exceptions/ import from exceptions' __init__.py's exports.
Specifically:
- exceptions/
__init__.py re-exports submodule-defined errors - submodules import BaseError via the package root (exceptions/, not directly from exceptions/base.py)
- package root (exceptions/) depends on submodules while submodules also depend on package exports
me too. I dont mind sharing my projects and if others find it interesting/fun, they can contribute to it too. Seeing those PRs on my repos was interesting

If it works, it's not hitting a partial initialization error. They are all the same BaseError. If that name already exists in sys.modules, it isn't evaluated again.
I made an edit for tree structure ^
Ooh
Basically the last comment
You get partial initialization errors (circular import) when a.py imports b.py and b.py imports a.py.
a.py isn't fully evaluated yet because b.py needed to be imported. So when b.py goes to import a.py the interpreter says "bruh".
That's the simple version. The circle can be N layers deep into imports as well.
The issue is the same regardless of the depth. a.py never finished evaluating before something else tried to import it.
Modify turtledemo/clock.py
Quick question of paranoia for yall. Is it normal for "employers" to be looking around on here looking for "freelancers"?
It's not the common case.
And if i import FeatureError from feature submodule first before BaseError in exceptions' init.py then this happens:
package/exceptions/__init__.py:
#from .base import BaseError
from .feature import FeatureError
from .base import BaseError
File "/project/test.py", line 1, in <module>
from package.exceptions import BaseError, FeatureError
File "/project/package/exceptions/__init__.py", line 2, in <module>
from .feature import FeatureError
File "/project/package/exceptions/feature/__init__.py", line 1, in <module>
from .something import FeatureError
File "/project/package/exceptions/feature/something.py", line 1, in <module>
from package.exceptions import BaseError
ImportError: cannot import name 'BaseError' from partially initialized module 'package.exceptions' (most likely due to a circular import) (/project/package/exceptions/__init__.py))
If someone is DMing you about a work opportunity, it's very likely a scam
(you can report them to @pseudo carbon )
not recommended, fragile, likely to break when you reorder imports or reorganize your code. feature.something should import BaseError from exceptions.base instead.
I suspected, because I got some guy with a linkedin link in his profile asking if Im a freelancer, hours after I had a onversation on here a few days ago about a multiprocessing project I was stummped with, and I doubt I said anything impressive.
put first import below?
the .base one maybe?
because FeatureError(BaseError)
If i am not wrong, won't doing from package.exceptions.base import BaseError inside package/exceptions/feature/something.py will lead to initialization of package/exceptions and hence evaluation of __init__.py of package/exceptions making it the same thing?
putting it below leads to circular import error but putting it first does not errors and works fine
Godly's point is accurate. I missed that you were doing that.
Then how am i supposed to fix this... I want to make all exceptions available under package.exceptions meanwhile submodules and subpackages inside package.exceptions able to import BaseError
good morning!

I don't believe it'll be the same thing, no - you should be able to import a submodule even before the parent module's __init__ has finished running. If you couldn't, from .feature import FeatureError would be a bug all on its own, after all
within the exceptions package, import the classes from the module that defines them
things outside the exceptions package can use the re-exports in __init__.py, things inside it shouldn't.
I've never thought of names in __init__.py as exports. That's interesting.
that's one way to use __init__.py, and a reasonably common one
lots of modules only re-export names from submodules in it
Isn't init famously used for that purpose?
Right. I've used it myself commonly. Just never associated the action of "export" to that concept.
Mentally, I've just said I'm adding TrackBearClient to the module's top-level namespace. However, that is just exporting TrackBearClient. Funny how things click years later.
src/trackbear_api/__init__.py lines 1 to 7
from __future__ import annotations
from .trackbearclient import TrackBearClient
__all__ = [
"TrackBearClient",
]```
And __all__ is a list of your exported names. And in fact, if you don't have a __all__ then several linters including ruff will special case ```py
from .trackbearclient import TrackBearClient as TrackBearClient
Hi
see https://docs.astral.sh/ruff/rules/unused-import/ for instance
01:40 in the morning and I'm here learning a new verb to associate with my code. neat.
haha, nice
Yeah, flake8 has a check for that as well.
yeah. in order to detect what imports are unused, you need to know what's imported to be used vs what's imported to be re-exported 🙂
Fairly certain that's how I found __all__. Looking for a way to clear that linting warning without using the import.
well. "using" the import.
all names being automatically exported from a module is just wrong. don't think this is a very hot take
i guess it is what it is
This worked without any errors regardless of the order of from .base import BaseError inside exceptions/__init__.py!
I changed from package.exceptions import BaseError to from package.exceptions.base import BaseError inside exceptions/feature/something.py.
probably isn't what we'd do if we were doing it from scratch, indeed
? What is that?
So inside subpackages/submodules of a parent package, i should never import directly from a package's __init__.py exports which imports both other names and subpackage/module names and rather by explicitly pathing to the actual file? That makes sense!
It's interesting that in 100 years, when software engineering is more mature, we will have a collection of antiquated practices that don't work and seem barbaric, like bloodletting.
hungarian names 😄
Isn't that future import is redundant?
it is
It is. It's automatically applied to all modules.
Automatically applied to all modules? How? I thought one future import affects only that module/file.py?
Not something I think about. It's just there. When we don't need it, I'll remove them all.
noxfile.py lines 43 to 48
"isort",
"--force-single-line-imports",
"--profile",
"black",
"--add-import",
"from __future__ import annotations",```
yep. that works because, even though __init__.py is still executing when feature/something.py runs, the base.py has already finished running, and so the package.exceptions.base module is already available in sys.modules with its full contents
Won't ruff or similar linters be enough to warn you where you are missing future import for annotations?
Sure.
isort is a linter
To be clear: This is my preference as a dev for my repos.
"wouldn't a linter be enough to do (the thing you're currently using a linter to do)" is a strange question 🙂
Thank you & Preocts a lot for your help
Now i gotta find out where i made this mistake and fix it
is it something useful to be added in ruff or some tooling where it detects such circular imports?
Is there any tool which helps detect such circular imports?
Potentially circular imports i mean
Your unit tests are a great way to detect those errors.
I actually don't know of a linter that detects it
How so? For python, it works perfectly normal as long as i import & export the BaseError before i import subpkgs/mods. Its a matter of order in this case if I'm not wrong
yeah, it's often a matter of order
btw, was the combination of @dataclass(frozen=True) and exceptions fixed? https://github.com/Preocts/trackbear-api/blob/c3f77b64cda489b87f6074eded2480ed74d73385/src/trackbear_api/exceptions.py#L34-L35
Maybe I'm misremembering, but there was some thing where __cause__ was being assigned and it errored out 🤔
in fact, it does error out if you do assign __cause__ manually
src/trackbear_api/exceptions.py lines 34 to 35
@dataclasses.dataclass(frozen=True, slots=True)
class APIResponseError(Exception):```
Like Preocts said, that's what unit tests are good for
Executing most of your code paths continuously, so when you break something you find out quick
I'm tempted to say that import order should be agnostic. However, I don't have a tool that reorders my imports randomly and runs tests on them. In that sense, I'm quite dependant on isort's order.
not really - unit tests don't check that you're importing modules in the same order as your users are importing them in, for instance
Unit tests change init.py's order of imports? 
!e
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class Foo(Exception):
x: object
try:
try: 1/0
except ZeroDivisionError as exc:
raise Foo(69) from exc
except Foo as exc:
e = exc
print(repr(e), repr(e.__cause__))
e.__cause__ = None
``` erm... what a weird error?
:x: Your 3.14 eval job has completed with return code 1.
001 | Foo(x=69) ZeroDivisionError('division by zero')
002 | Traceback (most recent call last):
003 | File [35m"/home/main.py"[0m, line [35m15[0m, in [35m<module>[0m
004 | [1;31me.__cause__[0m = None
005 | [1;31m^^^^^^^^^^^[0m
006 | File [35m"<string>"[0m, line [35m16[0m, in [35m__setattr__[0m
007 | [1;35mTypeError[0m: [35msuper(type, obj): obj (instance of Foo) is not an instance or subtype of type (Foo).[0m
and unit tests typically test only one possible order of imports, out of all of the possible orders your package's modules could be imported in
I think I'm lacking context on what kind of project this is
That would be an interesting testing solution to create.
Start from here
I'm not seeing high value with it, but it's scratching a "fun" part of my brain.
any kind, it doesn't matter. if you write code that works if mypackage.foo is imported before mypackage.bar but fails if mypackage.bar is imported before mypackage.foo, then your unit tests will only catch it if they import .bar before .foo
you most likely don't have a separate unit test that runs as a separate process just to see what happens if you import .bar before .foo
Hm, fair enough
!e
@chilly whale do you have any clues as to what in the devil is happening here ```py
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class Foo: pass
foo = Foo()
foo.cause = None
:x: Your 3.14 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File [35m"/home/main.py"[0m, line [35m7[0m, in [35m<module>[0m
003 | [1;31mfoo.__cause__[0m = None
004 | [1;31m^^^^^^^^^^^^^[0m
005 | File [35m"<string>"[0m, line [35m16[0m, in [35m__setattr__[0m
006 | [1;35mTypeError[0m: [35msuper(type, obj): obj (instance of Foo) is not an instance or subtype of type (Foo).[0m
Then I guess the solution is to mandate a canonical import order with isort
that only helps if your users follow the same order 🙂
Well, if the "user" is the same project, they would
Will be great for dumbs like me or beginners thinking it might be correct since python doesn't errors.
If it's a library, then I dunno
yeah, I was assuming library
You aren't dumb. None of us are testing for this in the conversation. I make the assumption my library will work. However, someday an issue might show up where a user found a way to break the imports.
yo
I haven't really released a 3rd party Python library but I guess I'd be more concerned with ensuring import order doesn't matter in that case
Tho i will need to be so explicit now. (In each subpackage, i have to type out full path of that file i want to import but Exception's init already exports).
Should i keep things as-is by keeping BaseError import first before subpackages access it? Is such a contract recommended?
That makes sense
good cause I had no idea 😄
||__cause__ you had no idea||
