#python-discussion
1 messages Β· Page 588 of 1
!doc math.e
math.e```
The mathematical constant *e* = 2.718281β¦, to available precision.
Edmonton Eulers
I meant that.
that's not a lot of hardware
canadiens winning stanley cup
I was thinking the Sigma function E
Houston Oilers.
The number e is a mathematical constant, approximately equal to 2.71828, that is the base of the natural logarithm and exponential function. It is sometimes called Euler's number, after the Swiss mathematician Leonhard Euler, though this can invite confusion with Euler numbers, or with Euler's constant, a different constant typically denoted
...
i wonder how many mathematicians pronounce it as "you-ler" / /ΛjuΛlΙr/
.wa s e
2.71828
eww
no diploma for you
Diplomas are overrated. It's the education that matters.
@silver plover i remember 2 yrs ago i hated coding now it makes me happy
both are important, tbh
you'll get further with an education and a degree than with only one or the other
As a man without a degree, I know.
what does the s argument mean
short
oo
yooo i just imported my first thing in py π
π
Euler's number
Text him... See if he responds.
The rate of change in an instant
ive been typing in his number for awhile now, how long is this number???
this is going to take forever
inf
Try using binary instead.
Text who? Euler? I hardly know her
π₯
I'll take the L on this one ngl
If you don't reach out, you never will...
this is going to take 10000....?
What the hell is that supposed to mean Dan
If you don't text someone because you hardly know them you'll never get a chance to get to know them.
You know, in the midst of my python projects, I think it'll be healthy to do fun or stupid projects so I dont get bored
Bars
Project Euler?
Octal?
What could that even be π€
0 repeating
https://projecteuler.net/
A site with loads of problems that are challenging, which you can tackle with programming
Hex?
ah, try base euler. e0001
Well played.
OH I thought we were still joking about Euler π
I was riffing on that but it's real projects.
I love math, so this could definitely be interesting
are they complex?
no rational person will spend so much time on these, right?
They're rational.
ok, raise your hand if you mispronounced Euler having only read it before finding out how it actually sounds.
ποΈ
i didnt actually, i read about euler in murderous maths, which explained how to pronounce euler
Ah, nice!
Yuler
Youler
ahh, the good old days, reading murderous maths and horrible histories in primary (elementary) school
sounds like u had fun
Back then it seemed so hard and we had no responsibilities
oyΒ·lr
not really no, primary school was a bit too easy
as in "Euler's gif"
In this economy? It's over $100 a barrel.
https://www.youtube.com/watch?v=sdWEGzWFcCc
no thanks, take back this gift cursed creation
This has to be the worst measurement system still in widespread use.
This video is a kind of follow up to my previous video on nuclear fracking. I've hinted at doing a rant about the awful awful units system the oil industry insists on using for a couple of years now, so here it finally is.
I suppose the only source (apart from my memory) is t...
another American invention?
too much high iq
Do not blame the US from imperial measurements. Blame the pirates for us still using them.
alexander the ok is british, btw
complaining about units used on british rigs in the north sea
I'm kinda surprised nobody asked about the pirates....
How are pirates even involved
Thank you!
just did lol
ts gave me such a fucking headache, now I learnt that I have to appreciate regex
for prefix in ["!e ", "!eval "]:
if reaction.message.content.startswith(prefix):
code = reaction.message.content[len(prefix):].strip()
break```
Thomas Jefferson, the 3rd president of the US, was a Francophile and ordered a set of standards from France. Pirates raided the ship and stole the standards. And the rest is history.
(it breaks)
Regex is wonderful!
the only word i understood is pirates
verb or noun
still, how does that relate to the US bad choice of unit measurement?
π΅βπ«
Imperial came from the UK. So it was what was used by the colonists before the US existed as a country.
Tomorrow ill change that for a pretty regex, along with the rest of my alike-stuff
Metric wasn't around until the French revolution.
You can have regex or pretty but not both.
A Francophile is someone who has a strong affinity, love, or admiration for France, its people, language, history, and culture
francophile sounds bad though
Indeed. And Thomas Jefferson was one.
what i'm thinking is pretty simple tbh
Very famously.
https://pythex.org is your friend.
cool, good to know the Brit used to have such a severe feet fetish they made it a unit of measurement
words ending with phile aren't so pleasent usually
TYYY
π€£
im an sportphile
π
wait i mixed spanish there
@raven urchin
import math
d = input("Enter the diameter of your pizza in inches: ")
Ο = math.pi
pizza_area = (Ο * pow(float(d), 2))/4
pizza_area = round(pizza_area, 1)
print(f"The area of your pizza is {pizza_area} inchesΒ²")
Snopes blocks ad blockers so I can't see that.
I made something like that once lol
hmm glorious
lets me see it
anyways, not-really tl;dr:
While it was true that physical items to demonstrate metric standards intended for Jefferson did not make it to him because of piracy, there was no plausible alternative history in which the delivery of such items would have overcome the political stalemate over establishing a standardized measuring system β no matter if it was the decimal-based metric system or something else.
At the time of Dombey's death, Jefferson was already convinced of the virtue of these ideas. Congress was not. As such, we rate the claim that piracy prevented the U.S. adoption of the metric system as "False."
pirates used to steal everything huh
Im going to make a price to area ratio now with if statments
zoomer-to-english translation: It's wrong
There's a lot more than just the pirates but that is an interpretation. Maybe if the standards had arrived Congress would've been convinced. Who knows?
And it's a fun story even if the interpretation is far-fetched. Jefferson could've had another set sent over.
very nice
lol yea
i thought there was an attempt by the us govt to switch to the metric system during the cold war but the public went bananas
that's humans for ya
They started teaching it in the 50s IIRC but it has not caught on outside of the scientific community.
Outside the country, however...
how are they cool with using the metric system for measuring bullets tho
Leave our freedom units alone.
That needs precision.
π₯
I'm sorry, I can't think of any other thing to say rather than such a generic zoomer emoji
You are not getting any arguments.
But the fact is that things that have smaller tolerances use metric.
I love how my Linux teacher keeps mentioning Galiger's travels when explaining why some commands do the same thing but at the same time are used differently
yup
analogies and metaphors have no place in CS
Yes. Cause we are killing parents and leaving orphans in CS.
That's not true. They can help open the door for a more detailed explanation. But you need to be careful with them.
damn...
CS is full of metaphors
We are aware of LLMs. Yes.
...not even that...
When a parent process is killed and leaves a child process running, the child process is now called an orphan process
at best, they don't introduce inaccuracies, at worst they make the current dev netscape
Think about that next time you kill a process
Kill all the processes. Got it.
kill the child first
processes aren't sentient, so i'm pretty sure you can go Machete on them
machete mentioned !!!!!
Murder the child and make the parent watch. Got it.
π
Dan
thanks for the regex thingy
They aren't sentient, yet.
I think my problem is fixed now
You're welcome.
Now you have another problem π
probably!
thats the magic of programming HAHA
discord y u hire gh devs 
oh it worked this time 
That's the way life works. Fix one problem and stumble on another.
The 9x19mm Parabellum cartridge, commonly referred to as just "9mm", was developed in Austria, hence the unit.
I didn't ask - how were all the tests? You ace all the classes?
ofc, most of them are either over or 2 - 1 point away from 90
very nice
gh devs?
there's currently a bit of a outage
Biophysics was the hardest and I got 89 theory and 87 lab :D
oh it's not just me
My gun knowledge is little to none. But thanks for the information. No idea what I will do with it tho :/
β€οΈ
Somehow I manage to have a typo doing β€οΈ - I is talented.
iet could do for a nice dystopian sentence, indict spmepne to become a computer process, get them stuck in a race condition
their official status page is lying, but others tell the truth: https://downdetector.com/status/discord/
Sounds like Tron.
lmao, i would watch that Tron
If you want more useless ammunition facts: in Russian/Soviet tradition, the caliber is measured by the inner diameter of the rifling, but in the rest of the world by the outer. So the 9x19 Parabellum's bullet is 9mm in diameter, but 9x18mm Makarov's bullet is 9.27mm.
It's like kilobytes and kibibytes
0.22 caliber is also 5.56mm
nah, in this case, I'll take my "blissful ignorance" pill, thank you very much
these guys are trying to disease us
Who knows what facts you'll need in the apocapylse
Having knowledge is never bad.
how do you even know this fix
I have no idea. I've never shot a live firearm in my life
I know it because of my time in the IDF.
because you killed them all first and shot dead firearms?
even occult knowledge which will get you targeted by fanatic cultists?
Knowing is half the battle π
yes
what's the IDF?
I think I know but I forgot
Internet de France
Israel's armed forces.
wouldnt that be IAF? π
Let's come back to Python
oh sorry
Israeli Defense Forces.
lol
aaahhh
That's the Israeli Air Force specifically π
nipping a kerfuffle in the bud
(and 5.56 != .22... close but it's a .223... wouldn't want a .22 in a .223 or vice versa)
.topic
Suggest more topics here!
That makes sense. Do they do python? 
Nope, but I have funny ideas
I imagine. There's Python everywhere.
the probblem with the topics is that they're bad
the dominican programming language HAHA
Suggest more topics here!
Programming, no. Tried making a language with friends in school umpteen years ago.
So suggest more. There's a link.
I never knew this google form even existed. No clue how to see the results
i think grey suggested some
Wanna hear something funny?
Always.
I hope someone does. We need new topics.
oh nvm, he did facts, not topics
Hi chat
yay or nay?
x = async lambda: None
Nyet.
i like it
That for loop i replaced with a regex was super annoying, because it worked, but was easy to break. So easy we didn't even notice when testing it.
I used THE EXACT AND ONLY WAY for it to work, and all others just wrote all the ways that didn't work.. So we thought I messed up the permissions or some ownership check of the messages, but it was formatting, it's always formatting π
a CPython core dev randomly appeared
I've tried making an esoteric programming language, but lost motivation π
yes hello
throw a pokeball at him
It's always formatting.
hi CPython core dev aggresive
I think the problem is that the topics are personal, rather than discussing something third-party. Very few people posted an actually useful PyPI package for example. And it's going to be those 3 people repeating it.
hru tonight?
what you decided from yesterday
now why not:
async if x == y:
...
if x async in y:
...

still writing it up, probably going to do async yield from
there is no ieq dunder i think
What would this do?
Maybe.
are you actually trying to pr this to cpy
no icontain
no
lol wut to that
a i mean, not i
__abool__, __acontains__ or whatever the dunder is
no
I see, you're preparing a new PEP for April 1, 2027
i dont like it
or may 21st 2026
whar
__aeq__ __acontains__ 
i think its too much
if boat.bilge > boat.reserve_bouyancy:
async boat
why the specific date
That hurts.
@wise imp what's the difference between event.dict["size"] and screen.get_size()?
April Fool's Day.
oh, didn't even think of it lol
We really should have more April 1sts in a year.
The day when we must believe everything on the internet.
365.25 aren't enough?
a real april first prank would be on the last day of march

got confused for a second

do you mean march or are you proposing we name months after categories of purchasable objects
english is exhausting
there's 365.2425 days per year
There are currently about 365.2421875 solar days in one mean tropical year
sure about that, godly?
Nuke English
You have my permission to troll people whenever you like
Standardize speaking in binary
or sign language
01101000 01101111 01110111 00100000 01100001 01100010 01101111 01110101 01110100 00100000 01101110 01101111
+, -
Is all i know in sign language
there's event.dict? anyway, you can just do event.size probably, but also, probably no difference in the values if you compare them at the same time? one is just an event, that's all

that's a tropical year, 365.2425 is the number of days in the average Gregorian calendar year
wow, thats insulting
nice try
w, h = (dim - 100 for dim in pygame.display.get_desktop_sizes()[0])
screen = pygame.display.set_mode((w, h), pygame.RESIZABLE)
pic = pygame.image.load("assets/temp.jpg")
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.WINDOWRESIZED:
screen.blit(pygame.transform.scale(pic, event.dict["size"]), (0, 0))
pygame.display.update()
elif event.type == pygame.WINDOWEXPOSED:
screen.fill((0, 0, 0))
screen.blit(pygame.transform.scale(pic, screen.get_size()), (0, 0))
pygame.display.update()
I'm just trying to make the screen resizeable and according to some old documentation I needed all this
hmm, so it seems
the Gregorian calendar has a surprisingly complicated leap year rule that results in the .2425
a year is a leap year if it's divisible by 4, unless it's divisible by 100, unless it's divisible by 400
unfun fact: there's disagreement of whether year 4000 is gonna be a leap year or not
it should be - it's divisible by 400
luckily we won't live by then
to make the window resizable, all you need is the RESIZABLE flag, resizing contents is, of course, a separate thing
ohhh I see
unless medicine will evolve insanely, and then we won't be so lucky
unless we add another exception to the rule filled with exceptions to make it slighter more accurate, and then maybe another exception around year 20 thousand
sure, but if we change the rules it's no longer clear that we can call it the Gregorian calendar
whats special about 4000 or 20k
that's basically why we haven't done it yet:
thus reducing the average length of the calendar year from 365.2425 days to 365.24225. Although this is closer to the mean tropical year of 365.24219 days, his proposal has never been adopted because the Gregorian calendar is based on the mean time between vernal equinoxes (currently 365.242374 days)
One guy tried to program a Hello World in binary and just quit midway throughπ
a smart fella programs hello world in python, and a text-to-binary converter in python that translates the first one
tbf if we have an exception for 4000 does that not include 8000, 12000, 16000, 20000?
π§
how about no...
i am not a smart fella
this is actually something fun, it sounds easy
the proposed rule would alter years 4k, 8k, 12k, etc to be common years, and then possibly another rule to alter 20k, 40k, 60k, etc to be leap years again
i program hello world in rust π blazingly fast π π memory safe π¦π¦π₯
tl;dr orbital dynamics sucks
"programming in binary" meaning writing raw machine code?
he was writting 0s and 1s, idk how legit that was
maybe he knows only binary
It was a youtube video about "the worst ways to program"
he tried in a minecraft book and quill, and had to farm for them π
this server is only english though
he also tried nintendo ds pictochat
you can use a binary to english translator though
the video was funny af, also he gave Vim an F.
SHOW SHOW
very nice
basically not at all
I guess it would be possible to write machine code in only 0s and 1s but in practice the only 0s and 1s are going to be physically on your CPU
me when I bin()
ET
you would just need an additional translation layer to convert the bits into actual data
he was translating from an ascii table
you can't write machine code with an ascii table
._.
then thank god my friend quit
imagine spending 3 hours writting meaningless 0s and 1s just to figure out it wouldnt work anyway lmao
let me find the video so yall suffer too
01101000 01101111 01110111 00100000 01100001 01100010 01101111 01110101 01110100 00100000 01101110 01101111
By then, we should develop technology that would slow down Earth's movement around Sun such that each year is actually 365.25 days. Not 365, because that would break a lot of existing software.
i'm gonna steal it thuri, everytime i wanna say "how about no"
i'm sure nobody would have a problem with this idea
He gave Vim an F tier on his "horrible" list (which means least bad)
that's hilarious, thats like getting Vs code in it for no actual reason π
no, let's slow it down to a round 360, that way we are matching with degrees
The tier was "The most horrible"
So uprank means worse.
the highest was his attempt of coding in ascii π

also somehow he liked coding in a minecraft book and quill π₯
you really like that emoji, huh, aji?
it's β’

Speed it up to 1 to have more consistent agricultural conditions
Yes, iteration fan, yes
like aboo with π©
and also Β©
oh so he was just writing a python program with each character in its binary representation
wait, true, going to 360 is not a slow-down, it's a speed-up
@dusty ember get weary pinged lol
yes, i kinda messed up the explanation
except people living in the sun
a-boo
hope I didn't scare ya
AAAAAA
if my ducks get scared, i am reporting y'all!
imagine you do what fix said, and end up ruining it for other planets, thats kind of funny
how long would it take to achieve such speeds in a way that we don't feel the effects of the acceleration?
and is such a speed even achievable
without disintegrating earth
that's a sacrifice I'm willing to make
probably about a zillion years
What fix says?
How much is zillion
^
We just have to increase the diameter of earth's orbit, ezpz
the trick is to do it backwards. No acceleration, just a lot of deceleration.
what's good

It's year 3000, we failed to stop producing too much greenhouse gases, so we just moved Earth further from the sun
gdi aboo
you were supposed to respond with π©
I'm a new man now

fine, so commission fix to make a weary_lemon or somthing
all ducks on this server are mine, my duck army
Grr
I feel like coding more
But I have like 13 hours straight coding

I should sleep
whar
hey aboo

sup
LEMONSAURUS
why did you crop it??
uh brb

my favorite lemoji 

i'm lowkey using basedpyright purely for autocomplete
It's just a silly fork of it
With based features
what features does it have
Based ones?
such as?
it adds some features that pylance has but pyright doesn't, changes some defaults to make type checking more aggressive by default, and adds the ability to set up a project baseline so that basedpyright in CI only complains about new stuff and ignores existing lines

No microslop
I don't think that's true
you guys will find any reason to hate on ms
I'm pretty sure features added to pyright get ported to basedpyright
out of curiosity, which features does pylance have that pyright doesnβt? itβs been a while since I last used pylance, but pyright has been pretty great for day-to-day work
the thing where parameter names show up if you hover over function calls is the big one I know of
semantic highlighting, lsp jump, completion, auto-import, a few more things
There's a list of things here: https://docs.basedpyright.com/latest/benefits-over-pyright/pylance-features/
docstrings for compiled builtin modules, hover and "go to definition" on operators and go to implementations are pretty cool
that's just the ones basedpyright has that pyright doesnt
"inlay hints" is the one I was referring to
Auto-completion, go-to-definition, and import suggestions while typing are already present in pyright
my info seems to be outdated
those things have always been in pyright
oh hot take but I canβt stand that
it gets all messy when I type
the other stuff looks cool though
hm, i just got it from https://github.com/microsoft/pyright/issues/1859 here
I too hate inlay hints in Python
inlay what
I havenβt enjoyed them in any language, but I havenβt tried them too much
I bet itβs a rust thing
yeah, I find them useful in Rust when chaining methods
called it
What's inlay hints?
iβd be fine with them if the LSP was actually able to keep up with me, but usually they just get out of date or mess with my cursor
Inline hints?
i just enabled it, am gonna try using it for a bit
itβs like where the editor shows you type hints on things that you didnβt actually add type hints for

they keep just poppin up everywhere and shiftin the cursor around
hate that
heh. I hate semantic highlighting
I have no idea how everyone else has decided that it's a good thing to have every word on the line colored a different color
I think it's fabulous. π³οΈβπ
In VSCode and Zed, there's an option to only show inlay hints when you press a button. In VSCode it's "editor.inlayHints.enabled": "offUnlessPressed", and I think the default combo is Ctrl+Alt.
i personally rather like it although my theme is comparatively low contrast
Like, legitimately. For me, it increases readability.
I wouldn't want it in written English.
I find it incredibly distracting.
With that enabled, a lot of inlay hints that would make the code unreadable become extremely useful. It's like showing the type on hover but better.
screenshot
neovim lets you do that, too
emacs has a command for it, too, I'm sure
Rust jumpscare
I have spent the last six hours wrangling demons in order to get my Rust shitpit code working properly
Real
days
powder that makes you say real
It's a good language
But by fucking God it's an exhausting language
months
Couple that with trying to spoof a hardware you literally don't own nor can verify its inputs due to a lack of documentation...
GG
Fuck you Logitech
basedpyright doesnt consider unions a type sigh
what do you mean?
Today's News : Linkdin layoff 600 employees

check ot0
smh post text as text
Even though they themselves provide jobs, they ended up firing people from their own company.
Β Β Β Β "tuple[str, UnionType]" is not assignable to "Tuple[str, type]"
Β Β Β Β Β Β Tuple entry 2 is incorrect type
Β Β Β Β Β Β Β Β "UnionType" is not assignable to "type"``` but that requires me to exit (n)vim
also i cant extract that into a type alias
Indeed, type[T] is for classes. a1 | b1 is not a class. If you want to accept arbitrary type hints as arguments, you should see TypeForm (it is stable, but for now only available through typing-extensions)
What's the library? And what function are you using?
msgspec.defstruct
by binding a key to vim.lsp.inlay_hint.enable(not vim.lsp.inlay_hint.is_enabled())
annoying thing too is that it allows it and it shows it in an example
Why are you using it instead of the class-based approach?
I should maybe try harder to use more vim
one of the fields im decoding has a hyphen and python doesnt like that
btw @chilly whale how do you say get your config across machines? like if you ssh into some server, how do you get same config as you have on your computer locally for like nvim or tmux
I don't change machines that often, so for me it's just manually cloning the repo with my settings
class Foo(msgspec.Struct):
banana_count: int = msgspec.field(name="banana-count")
class Foo(msgspec.Struct, rename="kebab"):
banana_count: int
or repos, actually - I've got neovim and tmux configs in different repos
mmm, that sounds useful and quick to sync, too, thanks
:o ty!
I would guess that defstruct is mostly intended for dynamically generating struct classes
that seems to be the implication yeah
although TypedDict doesnt seem to work that way
looks like this has been fixed actually: https://github.com/jcrist/msgspec/pull/1014, it's just not released yet
huh
!pypi msgspec
I m not getting what decorator is at all while creating class methods and how they can be used?
Are you talking about specific decorators?
I saw @classmethod in a code like this
def how_many(cls):
print("We have {} robots".format(cls.population))
But then the page where I saw this also said
Decorators can be imagined to be a shortcut to calling a wrapper function (i.e. a function that "wraps" around another function so that it can do something before or after the inner function), so applying the @classmethod decorator is the same as calling:
how_many = classmethod(how_many)
But then I wanna ask how can how_many.population possible
Btw the page is this https://python.swaroopch.com/oop.html
Did you understand how a method marked with @classmethod is different from a regular method from the example?
No and that's why I m confused
Normal methods ("instance methods") allow you to ask something or change something about a specific instance of a class. But class methods are about the class as a whole. In the example, you can see that you can do Robot.how_many() -- that's operating on the Robot class, not any particular robot.
Yeah and how do I use an instance method in class constructor?
I'm not godly, but I've got a script called putacc which rsyncs my account to another machine with the --files-from option
Self.method?
If you're in the constructor (do you mean __init__?) you've got self.
Yes, you can call methods on self inside __init__, just like in any other method.
what does the cc stand for?
Oh so I can create instance methods just inside init and if I m creating it outside then it's either a class attribute or a class method? But then why I needed the @ decorator?
"acc" - put my account
ah, not "puta CC"
are you ungodly?
I can create instance methods just inside
__init__
No, where did you read that? Instance methods are not defined inside__init__.
though you could
Not... specificly.
super().__new__() ?
This gets boiled down all the way to C level to create instance right
I suspect irrantional meant the initialiser, not the constructor
I mean you also used the word init in ur earlier message can u tell why is it special in terms of instance method then?

pretty sure __init__ is also referred to as the constructor
I don't think I understand what you're saying
Maybe you could open a thread in #1035199133436354600?
__init__ is just the name of the method Python calls on a new, blank, instance to initialise its stuff
its an initializer/setup though, not sure if calling it constructor would be appropriate
i would admit i used to think its the constructor
Except that __new__is better referred to as the constructor. And __init__ is for initialisation π
class Circle:
def __init__(self, diameter):
self.diameter = diameter
@classmethod
def by_radius(cls, radius):
return cls(radius * 2)
circle_one = Circle(10)
circle_two = Circle.by_radius(5)
print(circle_one.diameter)
print(circle_two.diameter)```This is one use case for the classmethod decorator. Circle.by_radius becomes an "alternate" constructor here, another way of creating a Circle instance.
I'm now realizing that A Byte of Python is a bad textbook if you're not already familiar with Java or another OO language and just need a crash course
everyone pays attention to the popular kid dunder init, thinking its the constructor. Meanwhile the real hero is dunder new, creating new instance object for you.
Ikrrr but then how can I create an class method? And what's the role of decorator @spice hill
It spends like 5 seconds on explaining what @classmethod does, and does it as part of a giant mega-example, mixing many things together.
Pretty sure our friend fix is not, themselves, a decorator, even with the @
Bro
syntax error
Since this is not a simple question, I'd recommend opening a post in #1035199133436354600, so that the conversation isn't lost in here.
Aight
A decorator takes another function, wraps it and returns another function (usually).
@classmethod marks a function as a 'class method', meaning the function is callable without taking an instance but rather class itself as its first argument
Pythonic is actually a glossary term π
https://docs.python.org/3/glossary.html#term-Pythonic
Done
good morning!
Speaking of... does anyone know a good free resource that explains the basics of classes?
Ohayo gozaimasu, eivl!
thats why we only and should only recomend it to someone that already knows one of those languages
def decorator(obj):
return "Decorated thing."
def func():
pass
func = decorator(func)
# being roughly equivalent to
@decorator
def func():
pass
print(func)``````
Decorated thing.```@unsure.9
What is a decorator a function? And it always starts with @?
OpalMist already cooked that answer for you
a decorator is code that writes and changes code
The @ introduces a decorator on a function, yes.
(There's also @ for matrix multiplication, but differently used.)
Transformation π
it appears neither is actually itself a constructor according to the data model and the constructor is the call to the class itself??? it appears __new__ may be more appropriately referred to as a "creator"
https://docs.python.org/3/reference/datamodel.html#object.__new__
So we are just passing a function in a decorator but why do we need to pass it any example?
Yeah, probably. But calling __init__ the constructor is arguably wrong.
Anyway, we're splitting hairs.
why do you need to modify a function, you mean?
Yeah...
bikeshedding at its finest
one of the most common usage you will see is to declare that function as the handler for a URL/endpoint
I'm not sure I understand.
MyClass(...) is seemingly what is the constructor (or at least the constructor expression)
https://python.swaroopch.com/oop.html but why they used the decorator here? @brisk gazelle can I create a class method without using it?
Yeah. My point is more that by the time __init__ is called the instance already exists. We're just polishing it off.
Do you know of a good free resource that teaches user-defined classes? (something you can read after Automate the Boring Stuff with Python)
do you mean @classmethod?
Ye
yeah, that was just clarifying for Aji
That particular example could access that counter attribute through the instance, so it doesn't strictly need to be a classmethod there.
It could also access it explicitly through the class name itself.
Like it's doing elsewhere.
when you declare that the method is a classmethod, it receives the class as the first argument, the same way that the instance/object of a class gets passed as the first argument in an instance method
Think of @staticmethod and @classmethod as describing the context the method receives. A normal instance method receives the instance, self. A class method receives the class. A static metho doesn't receive anything special as the first argument.
An instance method needs to be called from an instance: obj.method(....)
Because a class method provides just the class as context (the first argument, often called cls), you can call is via an instance obj.method() or via the class ObjClass.method().
A static method is just a function. Call it directly, call it via the class or call it via an instance.
remind me please, where can i throw in my code?
Tyyyy
pretty much anywhere you can put the raise keyword
Suppose this:
def deco(func):
def wrapped():
print("being called from wrapped() function.")
return func()
return wrapped
the deco is a function, which takes a function (func), and returns another function (wrapped) and the wrapped function returns the result of the original func function.
This is called the higher-order function. This is a kind of wrapping a function and adding a middle person.
def my_func():
return "Hello, world!"
my_func = deco(my_func) # this is what we call being decorated.
result = my_func()
print("Result:", result)

!paste
So that everyone can easily read your code, you can paste it in this website:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
thx
Tyyyyy
what is pytest?
Teaching is hard. π
A tool for running unit tests. With many cool options.
unit tests?
!pypi pytest
so this is a program that can make up a short story for you based on the seed you put in: https://paste.pythondiscord.com/ZGNA
One of the usage: test your code before pushing so that you don't have unexpected bugs from new commits/updates and everything works as you expected
Unit tests are functions which exercise little bits of your code and check that they do what is intended. You write a heap of these, and it finds bugs, or checks that changes you've made still do the right thing. Etc.
peak
now write a program that finds a specific combination of the story
wdym "finds"?
trial and error different seeds until you get the story you want

not on the top of my head
so here's the meme seed which found a LMAO type combination of characters and events: 674269521337
i dont need to activate venv for a new project in pycharm right?
it does it for you
Oh right, CS50P
yeahh, thats a good one, i just have never done it, and i was in a headspace thinking of a book
To conqueror the world
I had to for class
alexander Aji the great
Hi
hi
programming was my second option after structural engineering, then I realized that im not good at chemistry
you still a student?
uni student, but yes
oh
Yo guys I am making a project
Please elaborate at your convenience.
level up from scratch πͺ
I am making a project voice command activation which runs without a seeable window, a d uses a local AI model to ans queries else use wikipedia and can open apps, write for you etc
what exactly is that ai model
It can even tell you about your own c specs and temps etc and what is using ur ram and etc
I am still finding Models, I have tried Qwen Coder 7B and 14B
an ambitious project
gemma 4 π
One sec
Does it have the capacity to delete files?
ts can run on mobile btw ^
One sec
Yea
Also it does not have capacity to delte files, that is still in progress as what if it deletes a same named file in another directory which is important?
I'm still training it
And I wish to make it into a application instead of a python file
But that's for layer
pyinstaller
!paste
So that everyone can easily read your code, you can paste it in this website:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Pyinstaller makes exe files which is good for instant butttt I want to make it so that it does not get flagged by windows defender
then u have to pay to get a cert π
Yeah
In blackjack, we can always think of aces as 11, unless it would cause a bust, in that case it would be 1. Total the hand and treat all aces like 11. If your hand busts, subtract 10 until your hand no longer busts or you're out of aces
def handle_aces_pls(self):
list_of_cards = self.hand.cards
dupe_list_of_cards = list_of_cards[:]
ace_list = []
for card in dupe_list_of_cards:
if card.value == "ace":
ace_list.append(dupe_list_of_cards.pop(card))
else:
pass
aceless_value = 0
for card in dupe_list_of_cards:
try:
aceless_value += int(card.value)
except ValueError:
aceless_value += 10
if len(ace_list) != 0:
for i in range(len(ace_list)):
if aceless_value + 11 > 21:
return 1
else:
return 11```
im doing all this currently
i love how i was doing this to learn classes originally
Try it with the logic I mentioned above. What you have here is quite overkill
Having a certificate is quite hard
and thats what im having the least problem with
i mean does it work
its easier for me to wrap my head around
To get the certificate I must make the app perfect yk? And stuff
What I mentioned will work perfectly
does my code work?
there's no reason you should be duplicating your hand. All you need is a function that returns the score of your hand
I have already made it so that you can just say a code word and the AI will auto start
It does far more than it should be
why do you add 10 when a valuerror occurs
king jack queen
they are 10 ?
if it's a number, add that number
if it's j/q/k, add 10
if it's ace, add 11
but str
hm but cant you like map those into 10s before than waiting for a valueerror
class Deck:
suits = ["spades", "clubs", "diamonds", "hearts"]
values = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"jack",
"queen",
"king",
"ace",
]
def __init__(self):
self.cards = []
self.make_cards()
def make_cards(self):
self.cards.clear()
for suit in Deck.suits:
for value in Deck.values:
card = Card(suit, value)
self.cards.append(card)
def count_cards(self):
return len(self.cards)
def shuffle(self):
random.shuffle(self.cards)
def deal_card(self):
return self.cards.pop()```
this is my deck class
def score_hand(hand):
aces = 0
total = 0
for card in hand:
if card.value.isdigit():
total += int(card.value)
basically i need those to be strings to make them be able to be converted into a readable string
yes
ie king of spades or so
def score_hand(hand):
aces = 0
total = 0
for card in hand:
if card.value.isdigit():
total += int(card.value)
elif card.value in ('jack', 'queen', 'king'):
total += 10
how about now?
also yes
I have never played black jack so Idk how to help lol
def score_hand(hand):
aces = 0
total = 0
for card in hand:
if card.value.isdigit():
total += int(card.value)
elif card.value in ('jack', 'queen', 'king'):
total += 10
else:
total += 11
aces += 1
now?
Man i got some bad news today
What is ut
choose aces?
the player never chooses
it's ALWAYS 11 unless you bust
then it's 1
idk the game tbh
that's it
ok
ok
i get that
My neck is legitimately screwed multiple severe herniated discs
ok, now we need to handle the bust
but i kinda have to keep track of aces tho
if we're over 21 and we have aces in our hand, we can subtract 10
I already am in my example
like for the dealer
no you don't
you just need a function that scores your hand
that's it
you don't score a dealer's hand until they flip their 2nd card
for soft 17
Yup drunk drivers are a whole different breed of moron
right now, this JUST scores the hand and nothing more
you can add another condition after to check for soft 17
yeah i get that
"if score_hand(hand) == 17 and "ace" in dealer.hand.values:"
this is slightly pseudocode, but roughly like this
i get that
we don't care if the hand is scored with an ace initially
don't try and do too much in a single function
keep them as simple and general as possible
wait hold on
it's better to have 3 simple functions than 1 complex function
but cant the dealer hit?
yes, they MUST hit on <=16 or soft 17
that happens after my turn ends right?
yes, once all players have resolved, the dealer goes
but the cards he hits are revealed?
ok that doesnt really matter in my code
move on
that's it
after the players go, you reveal the dealer's hand and score it
you should know if the dealer has blackjack initially though
if the dealer is dealt blackjack, it ends
everybody loses if the dealer is dealt blackjack
wait so my blackjack gets overriden by his one?
unless you have blackjack too, then it's a push
elaborate
push means tie
you should keep track of the dealer's stuff internally even if the player doesn't have that information yet
so you know if they're dealt a blackjack
the player doesn't play out their turn if the dealer is dealt a blackjack
wiat what
how do i remove an added file from git
1v1
I get dealt a card, dealer gets a card (face down). I get dealt another card, dealer gets another card (face up)
so they just get 2 cards and it s over?
πΏ
if the dealer's face up card is a 10 value, they peek at their face down card
woah i gotta completely nuke my game function
if their face down card is an ace, the round automatically ends
if you ALSO have blackjack, you get your money back
otherwise, you lose
Don't nuke people, nuke code
- Alex
aight imma try to do something
were u writing it in notepad before?
it also shouldn't be your player class that scores the hand
no vscode
it's the game's responsibility to score the hand
my brother took 11th grade html in notepad
treat your card/deck/player classes as if they could be used for any card game
it should be outside?
but my player class is only for my blackjack
ideally you would have a Blackjack class
that is pretty much what it is
sure, but when learning classes, it's a good idea to keep them as simple as possible
it should be a generic "player" class. It's something that holds onto cards
it's the game that gives those cards meaning
i have a hand class for that?
how to convert the string like ''10 -20" into [10, 20]
then what's the difference between player and hand here? If I were to make those classes, the Player class would also keep track of the money, have a name, etc
with str.split
serialize with str.split
serialize?
thats what u call it right
this isn't the context I would use that term
serializing a string to this array
Tokenise. Kind of the reverse if serialise, in a way.
I'd maybe say "parse"
oh yeah
ig the player class is used to run somethings that will happen on both dealers side and players side
Serialising is typically transcribing something to a string or bytes.
parsing/tokenising is the other way
you could use the Player for dealer too, sure. Maybe add an attribute for "is_dealer" or something
s = "10 -20"
parsed = [int(x) for x in s.split()]
print(parsed)
"Serialize" usually refers to converting some arbitrary object into a byte array, usually so you can store it or send it over a network
yeah my bad i used the wrong term π
"deserialize" maybe
but that feels like too strong of a word for a .split lol
parsed = list(map(int, s.split()))
functional programming guys.
what does map do
calls a function on every element of another iterable
i also hv to convert those numbers into int too
Takes a callable and an iterable, and passes each item from iterable to that callable
data = ['a', 'abc', 'abcde']
let's say I have this list
and I want a list of all the lengths of these strings
can you tell me what that would look like @quartz fulcrum ?
a loop?
no, just what would the list look like
yeah, the map just makes it even easier
len(data)
Of each string
no, that gives me how many things are in the list
def score(self):
aces = 0
t_value = 0
for card in self.hand.cards:
if card.value.is_digit():
t_value += int(card.value)
elif card.value.lower() in ('king','jack','queen'):
t_value += 10
else:
if t_value + 11 > 21:
t_value += 1
else:
t_value += 11
aces += 1```
does this work
You need to give the length of each item inside the list
Operators like map are typically used instead of a loop.
no, we can't determine an ace will be 1 until after we've finished scoring the hand
we need to total the full hand, then we can retroactively correct the score if necessary
ok
def score(self):
aces = 0
t_value = 0
for card in self.hand.cards:
if card.value.is_digit():
t_value += int(card.value)
elif card.value.lower() in ('king','jack','queen'):
t_value += 10
else:
t_value += 11
aces += 1
```
Though in Python list comprehensions and the like are more commonly used than map
boom
no idea, i can only think of loop
I'm just asking you what the list will look like in the end
I'm not asking you about any code
ann int
when you write code, you should know what result you're trying to achieve
Not quite. What if this sum is greater than 21 and you have an ace?
["a", "ab", "abc"]
Now create a list literal with each item's length, just type it yourself, not code.
yeah thats the first thing that came to my mind
if you don't know what the result will be, how can you write code to work towards that result?
[a , ab, abc]
!e ```py
lst = [1, 2, 3]
loop
result = []
for x in lst:
result.append(x**2)
print(result)
map
result = list(map(lambda x: x**2, lst))
print(result)
comprehension
result = [x**2 for x in lst]
print(result)
oops
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | [1, 4, 9]
002 | [1, 4, 9]
003 | [1, 4, 9]
1

dude what do i do
and len('abc')?
Exactly what I said in my first message to you
my bust check logic is in my game function
link pls
3
and len('abcde')?
5
Why do i feel like we are making wizard look like the python interpreter 
ok, so what would that look like in a list?
text = ['a', 'abc', 'abcde']
if I want the len of each of these strings?
[1, 3, 5]
yes exactly
because we are-
A wizard larping as a Python interpreter? What has the world come to?
text = [len('a'), len('abc'), len('abcde')]
we can think of it like this
but we can use map
Like his each output is exactly how in a REPL would be
he ain't even putting words. Quiet straightforward result
!e
text = ['a', 'abc', 'abcde']
print(list(map(len, text)))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
[1, 3, 5]
mapping len to this list will give us that same result
aight
bt i think im gonna need to rewrite my game function for that
hiiiii
what is map in this code
!doc map
map(function, iterable, /, *iterables, strict=False)```
Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterables* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. If *strict* is `True` and one of the iterables is exhausted before the others, a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) is raised. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](https://docs.python.org/3/library/itertools.html#itertools.starmap).
Changed in version 3.14: Added the *strict* parameter.
ohhh
If you scroll up I just explained it above
.
thansks
ah ok...is it possible to map lists only>
no, any iterable
!e
text = 'python'
print(list(map(str.upper, text)))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
['P', 'Y', 'T', 'H', 'O', 'N']
so it will create a new list, always?
no, map returns a generator iterator
it creates a "map" object
You can use any container which consumes that generator
but I'm calling list() on it so you can see the result
tuple(map(int, my_list)) works too
!e
text = 'python'
print(*map(str.upper, text))
Notably, the map object does not actually execute the mapping function until you consume it. Converting it into a list is one way of consuming it.
:white_check_mark: Your 3.14 eval job has completed with return code 0.
P Y T H O N
btw
(iterator, not a generator specifically)
im gonna need to make a computer computing function too
Oh yeah
i am too biased towards generator π₯
Thanks for correction
I have to look up the definitions of the terms generator, iterator and iterable every time I need to use them.
okk..
that's definitely unusual

i thought it's pretty clear
why do i share this problem too?
I'm exaggerating a little, but I do think they're easy to mix up.
I feel like I see a lot of other people having the same issue.
they also overlap quite a bit
i call anything a generator which uses yield, iterator when its just implementing iterator protocol and iterable is any object returning an iterator
it's like a square/rectangle problem

yes
str() doesn't take iterable... Had to use "".join(...)
broke my intuition/prediction as tuple/list/dict/set takes an iterable
dict() takes a mapping
it works with both by checking if it has keys&getitem and then iterable
russia has a great memory 
isn't that a mapping just in more words
I ain't putting a print bro
what was the advantage of switch statements over chained if-elif
matching shape
match-case*
!pep 636
keys&getitem are the same kind of mapping as what you need for **kwargs but not sufficient for collections.abc.Mapping, and dict([(1, 2)]) works even though it doesn't have keys
As the name says, Structural Pattern Matching
yeah, mapping is pretty loosely defined in regards to what dict wants
ok so
in blackjack
1v1
i get a turn and the dealer gets a turn right?
so when is it scored
it doesn't alternate
the player goes first and hits (asks for cards) until they stand (no longer want cards)
if the player busts, it just ends there
so i just rewrote my logic for no reason
Is it just me or OOP is a little bit hard haha
if the player stands with a value of 21 or less, then the dealer takes their turn
It's a pretty big jump in complexity and kinda reframes how you have to think about things
Most programming concepts are difficult when you first encounter them.
So I need to be scared, fu*k -.-
OOP is also a big area
why be scared?
There are parts of it that are harder than others
OOP is a hoax anyway /hj
Well... str() does accept iterables as the first argument...
We all figured it out eventually, you can too
yeah it just calls the __str__ of that instance
No, you shouldn't be. It's difficult at first, but it gets easier as you get more familiar.
the score function?
best way to use free ai forever in pycharm?
you can't really have a bust function without a score function that works
whenever the player hits, you'll score their hand
i have student developer pack still cant get it./
wdym
you have a value function and a score function and I don't understand why you have both
just get the scoring function working first, then you can continue
you nearly have it
let's say for example the hand is 6, king, ace
we go through first scoring everything (with ace as 11) and we calculate 27
6 + 10 + 11
after we score, we can say "if we have over 21, but we scored an ace, then subtract 10"
my scoring does that
I mean in a sense it doesn't consume its items to write a string of those items. It just calls dunder str of that object
Like how tuple & list consumes items and creates a tuple/list container of the given object
Im learning from course, and she said that we're gonna use big guns now haha
sounds pretty reasonable that str() would call the object's __str__
Yeah, I understand what you wnat to say
nope
I could only think of using "".join(iterable) at the moment.
basically join
str.join is what you want
assuming the iterable contains only strings
str.join does call dunder str of the items consumed from iterable, right?
no
str.from_iterable as you describe it could only be a less-general (and less-useful) version of str.join
no, the iterable needs to be made of strs in the first place
you couldn't ''.join(range(5))
Oh yeah that's why i also do map(str

, iterable)
HEHEHE