#internals-and-peps

1 messages · Page 53 of 1

sudden sun
#

Hello

#

I'm new here

sand quest
#

Welcome

unkempt rock
#

i have a quick little syntax question

#

how do I say is not bigger than in python

#

!<=

north root
#

less than

#

bigger than would be > and less than would be <

unkempt rock
#

I am running visual studio code
and , opened a file which is present in C:/users/com/Downloads/File.py
when i run the code, try to import something it checks for the file in directory C:/users/com/ and not in current directory

#

@cloud crypt u figured out a way to get the address of a memory view yet?

cloud crypt
#

I meant I just generally like their concept

#

I actually thought several times what would happen if I messed with process memory writing, but I am too afraid python would just segfault :p

astral forge
#

I used process memory writing for some bots and I had not yet a segfault error o:

cloud crypt
#

I meant writing to python's process

unkempt rock
#

U guys mess with process memory and it’s fine, I do selenium.webdrivers.Chrome() and it segfaults 😒

#

How to prevent my python program from reverse enginerring and cracking

#

I have added the authentication method on the start,

flat gazelle
#

PyArmor

unkempt rock
#

what is pyArmor

#

Wow that’s a dick move 😂 and still won’t help really

flat gazelle
#

A way to protect your python program against reverse engineering and cracking

unkempt rock
#

(I mean sure it’ll help a little)

flat gazelle
#

Imperfect obviously

#

Python is pretty bad at not being cracked. C, C++, Haskell, ... do much better

unkempt rock
#

Always wanted to try and make an uncrackable c++ thing using intel’s SGX, but idk if it’s possible :/

#

At least cracking

#

They could easily break the execution of code when my python program check for authentication

#

@unkempt rock I am using PhantomJs because headless chrome does not allow clipboard copy/paste

raven pike
#

hello guys, so i wonder if there are any tools where i can store both indexes and its values in a data structure? do python have built-ins for that?

#

basically i dont want to lose my order of values

flat gazelle
#

You can store (item, index) tuples

final whale
#

OrderedDict maybe

north root
#

lists are ordered

hazy anchor
#

as long as you dont need to access by index :p

raven pike
#

ordered but i will mess up with data, so i need to change indexes when i operate along

#

so when i sort the data, a new index order is needed

#

ordereddict? i'll check

#

@flat gazelle how do i do that? any starting tips?

#

@final whale how is this one structured?

flat gazelle
#

[4,5,7] -> [(4,0),(5,1),(7,2)]

#

Another option would be a custom list subclass

unkempt rock
#

@raven pike you can use dictionary

raven pike
#

i want to use dictionary actually, i havent used dictionary in my project

astral forge
#

you can use a list with tuples and sort the list by the tuple with the index. ``list.sort(key=lambda tuple: tuple[1])` where 1 is the index of the sort index

raven pike
#

i'm dealing with pandas, and have to do row by row cals. so i need more faster operation instead of using pandas built-in operations

#

they are so slow

astral forge
#

Pandas is partly writting in C, you most likely won't write a function in pure python as fast as pandas built-in functions are

unkempt rock
#

when no languages was developed

#

how was the first programming language written

raven pike
#

i mean using groupby for example is costly, however i can do that in python if i know what i'm doing? that's my thought process

astral forge
flat gazelle
#

Connecting transistors together until they compute things

unkempt rock
#

How was the assembly language compiler compiled

peak spoke
#

That's probably more fitting for offtopic

raven pike
#

i'm excited that python is considering type hinting more and more. i love it's not strict, and it's rather declarative

unkempt rock
#

the reason why c++ is hard because the creator of cpp doesn't knew good english

#

and their documentation isn't proper enough

tawdry gulch
#

Python already has type hinting for functions which is cool : )

narrow kettle
#

the reason why c++ is hard because the creator of cpp doesn't knew good english
...wut this is the dumbest thing ive read today

boreal umbra
#

I didn't explain myself very well in the python ideas thread I just replied to

#

But I don't think there's going to be much discussion there.

red solar
#

yeah tf, the creator doesn't write the c++ standard

#

it's an international effort

unkempt rock
#

In a nested loop, does the continue keyword only affect the current loop that the keyword is in?

#

for instance:

for index1 in list1:
    for index2 in list2:
      if index1 == index2:
         continue
#

will the continue in list 2 affect list 1?

whole glacier
#

Yes it won't affect the outside loop, it affects the closest loop

#

Which is the one looping over list2

unkempt rock
#

Second question I have is what the hell was Nicolas Swift thinking with his A* algorithm?!

flat zealot
#

@copper kayak go to the help channels mate

copper kayak
#

oh ok

tawny charm
#

You're in good company then.

wheat scaffold
#

heyy

#

?

#

any 1>

grave jolt
#

What type do DAYS and MONTHS have?

final whale
#

whoopsie

#

days and months are tuples of strings

#

want me to delete and take it to a help channel ?

grave jolt
#

maybe

#

yes

final whale
#

deleted and moved to a help channel to avoid cluttering

unkempt rock
#

Is there really no way in python to parse * as a command line argument? I think argparse can do it, can anybody confirm?

grave jolt
#

@unkempt rock This is not a help channel. Please read the channel description. Check out #❓|how-to-get-help

unkempt rock
#

@grave jolt already did some hours ago

grave jolt
#

🤷

#

You can ask again.

#

Not all questions are answered immediately.

unkempt rock
#

alright, but if u know the answer u can just type here.

radiant fulcrum
#

what exactly is the base type for a iterable object in python?

#

because list, tuples, dicts can all be iterated over

#

but what is their base object type then if you were going to type hint it?

brave badger
#

collections.abc.Iterable or typing.Iterable iirc

spice pecan
#

You'd use typing.Iterable, yeah

flat gazelle
#

They do not have a common base type afaik, you need either (__getitem__ for int and __len__) or (__iter__). Not sure if an abc can specify this

radiant fulcrum
#

it seems they do fall under typing.Iterable still

#

according to how isinstance sees it

peak spoke
#

Being an iterable is just that the interface exists

radiant fulcrum
#

mhmm

peak spoke
#

There's no common type but checking with the abc should work

unkempt rock
grave jolt
#

Please don't ping random people and don't advertise your help channel.

unkempt heath
#

Can someone tell me how to focus on profrraming fully??

#

*programming

brave badger
#

@swift gust This is not really the appropriate channel to get help from, you might want to consult #❓|how-to-get-help

swift gust
#

im sorry

unkempt rock
#

Hello, anyone remember what is the setting jSON to set to auto clear console before a run with VS?

astral forge
#

(And wrong channel to ask for help)

unkempt rock
#

thank you and sry

unkempt heath
#

Can anyone tell me how to fully focussed on progrraming

#

😆

shy vine
elder junco
#

👍

minor sinew
#

are immutable dictionaries a thing in python?

#

or maybe a read-only dict

brave badger
#

afaik there isn't, but you could always implement one yourself by subclassing collections.abc.Mapping

minor sinew
#

actually i think i have a workaround. i'll just let the dictionary be allowed to change and then i'll just commit the contents to a db, which was what i was going to do anyways

#

it's really true when people say 99% of ideas are just dumb lmao

unkempt rock
unkempt rock
#

Can someone please explain atomic operations in python ?

unkempt rock
#

Python has a lock (GIL) that means only 1 thread can run at once - any operation during which the GIL cannot be released is atomic in python

#

So a lot of operations on builtin types are atomic

#

(This is not the same as atomicity on a processor level, or in lower level languages, but those don’t really matter here)

#

I think this translates to any single python bytecode instruction is atomic? (Or something like that)

smoky ginkgo
#

Mentioning this here based on @unkempt rock's recommendation but I am looking for someone who has used pyinstaller to help me sort out some dependencies

unkempt rock
#

(Wasn’t sure what other channel to recommend)

#

What’s the issue with dependencies?

noble latch
#

what's really the point of an elif if you could just keep making if statements?

astral forge
#

You can include a default case after if, elif, elif, elif, else

noble latch
#

ahh ok

astral forge
#

else will run when no other (el)if statement is executed

noble latch
#

yeah, thanks for explaining :D

narrow kettle
#

what's really the point of an elif if you could just keep making if statements?
because a chain of ifs is not semantically equivalent to a an if elif

prime parcel
#

I am also interested in this question. Is there any difference in how code is executed if you use a bunch of ifs as opposed to a bunch of elifs?

peak spoke
#

All the ifs are executed, but an elif only gets executed when the conditions above it didn't pass

#

an equivalent to elif is

if cond:
    ...
else:
    if elif_cond:
        ...
``` but you can see why the elif was included when indentation is syntax
prime parcel
#

Awesome! Thanks for the explanation.

unkempt rock
#

hi
i need some little help
i want to imprt file in my script , but the file is not in the same diractory
how i can do it

lost nexus
daring siren
#

I'm confused. How can a = b or c work?

astral forge
#

a will be a bool

radiant fulcrum
#

It takes which ever value is True or False if both are false

#

that was a bad method of explaining that

peak spoke
#

Not necessarily, pyhon will evaluate the truthy values of the expressions and return the first result that's True or the last one

daring siren
#

No, like:

#

!e

a, b = 2, None
c = a or b
print(c)
fallen slateBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

radiant fulcrum
#

its the same principle of doing:

if b or c:
  # one of those values is true```
daring siren
#

Oh, sorry. I sent the same over there

astral forge
daring siren
#

Yeah, I get what it does, I'm confused as to why however

radiant fulcrum
#

Oh interesting so it will take the first value if both are true? @astral forge

daring siren
#

Anything that is not False or 0 can be cast to a True, correct? Why doesn't that return a bool?

peak spoke
#

Everything can define its own bool value. For the why, why not? They are not boolean operators

astral forge
#

@radiant fulcrum I was expecting a bool, so that is completly unexpected for me xD

#

But ye, seems like it does

peak spoke
#

At least not in the same way as & or | are in other languages that is

grave jolt
#

This is called 'short-circuit evaluation'. It can be useful to pick the first non-falsey value:

config.get("user") or config.get("username") or config.get("user_name") or "<default>"
#

The cool part is that it will not evaluate expressions it doesn't need to. Here, for example, if config.get("user") succeeds, it won't compute the other expressions.

astral forge
#

Well, it makes sense as I used the same feature in js before

peak spoke
astral forge
#

I just thought it would be a bool in python... 😂

grave jolt
#

In one help session I gave this example. Maybe it's a bit too contrived, but it demonstrates the point, kind of.

#

!e

class First:
    def __init__(self, fn):
        self.fn = fn
        self.computed = False
        self._value = None
    
    @property
    def value(self):
        if not self.computed:
            self._value = self.fn()
            self.computed = True
        return self._value

    def __bool__(self):
        try: self.value
        except: return False
        else: return True

    def __repr__(self):
        return f"First(lambda: {self.value!r})"
            
print(First(lambda: 1/0) or First(lambda: a) or First(lambda: "hello"))
fallen slateBOT
#

@grave jolt :white_check_mark: Your eval job has completed with return code 0.

First(lambda: 'hello')
astral forge
#

You can eval code in here?

grave jolt
#

Here I take advantage of lazy evaluation. .value is a 'lazy' property -- it doesn't get evaluated until it's demanded.

astral forge
#

ô.o

grave jolt
#

Helpers can do that

#

Others can do that in help sessions, if I'm not mistaken.

daring siren
#

Gotcha! I think. Thanks!

unkempt rock
#

helll

#

i need help with pyinstaller

#

failed to execute script

grave jolt
#

Please don't advertise your help channel.

unkempt rock
#

also, works when i compile in console mode, and it looks like pyinstaller compile and includes all file in onefile but can't file them during execution

lost nexus
#

I may of missed something in PEP622, but what happens if a function returns a Boolean, or an integer? Since true can be evaluated to 1 and false 0.

match f():
  case 0:
    print('x')
  case False:
    print('y')
  case 1:
    print('a')
  case True:
    print('b')

Ex, if f returned False, would the first and second case run, would they both run, or would it break after the first case succeeds?

magic python
#

is there any push to make anything that accepts a string accept a pathlib object? sometimes something will accept both, sometimes it'll work with pathlib.Path object but i'll get a linting error, and sometimes I'll have to convert to a string

flat gazelle
#

Most of the standard library should with both

magic python
#

it does ( though i just had a linting error using shutil with one ), but some other modules don't. Maybe I should look at the source for something, I don't know how they're typically handled, if a pathlib obj is passed is it converted to a string, or if a string is passed is it usually converted to a pathlib obj?

peak spoke
#

Probably the former for most things considering they already used those

magic python
#

so converting to string and then using os.makedir would be prefered over Path.mkdir ?

swift imp
#

Wait you're going to be able to use match as a switch statement?

#

The way I understood it, it was for determining comoposition of objects

magic python
#

@swift imp i never worked out what you were doing with .pdbrc

swift imp
#

What didnt u work out?

magic python
#

do you have a link anywhere to what you were talking about?

#

you were talking about it as though there was some sort of different approach, using pdbrc, to putting breakpoints in code

lost nexus
#

I'm pretty sure match is possibly Python's future implementation of a switch statement from C++, or a match statement from Rust.

swift imp
#

@magic python are u on linux or windows?

magic python
#

mac os

swift imp
#

uhg

#

well

magic python
#

all pdbrc does for me is provide an alias for interactive ipython session from within ipdb

swift imp
#

you have a file called .pdbrc that goes into your HOME directory

magic python
#

yeah i have that

swift imp
#

ok

#

so

#

add a line like

#

b <path to a file you want to do a breakpoint>/file_you_want_add_breakpoint_.py:<line you want to add breakpoint>

magic python
#

in ~/.pdbrc ? and this is easier than putting breakpoint() where I want a breakpoint? It looks like more work, but maybe i'm missing something

swift imp
#

when u fire up ipdb you'll see that the breakpoint is added

#

its less work because you don't have to change the file you are debugging and then manually remove it later

#

So, don't use the .pdbrc file, you have to manually add that breakpoint() and then remove that breakpoint() when youare done

#

where as you put that line your .pdbrc and it only becomes active if you start ipdb

magic python
#

interesting, yeah maybe that could be handy 🤔
where can i find documentation on this?

swift imp
#

just look up docuimentation for pdb

#

anything you would do in pdb, you can do the pdbrc

magic python
#

it's not documented in there afaict though

#

i mean - what you've written would be a pretty good guess given the documentation i've linked

fallen slateBOT
#
Command Help

!pep <pep_number>
Can also use: get_pep, p

Fetches information about a PEP and sends it to the channel.

molten lotus
#

oops wrong

weak rivet
#

!pep 478

fallen slateBOT
#
**PEP 478 - Python 3.5 Release Schedule**
Status

Active

Python-Version

3.5

Created

22-Sep-2014

Type

Informational

unkempt rock
#

Python has a lock (GIL) that means only 1 thread can run at once - any operation during which the GIL cannot be released is atomic in python
@unkempt rock thnx

fossil barn
#

python is the best programming language

grand folio
#

python is the best programming language

unkempt rock
#

Hey can anyone help me to build a python script to automate filling email address in html form using selenium and regex

#

*any html form ( regex use is compulsory)

wide shuttle
#

Hello, @unkempt rock, this is not a help channel, but a discussion channel to discuss the Python programming language itself. For shorter, more general questions, #python-discussion could work, but we also have up to 32 help channel available (dynamically scaled), see #❓|how-to-get-help.

#

We're slowly moving into the final phase of the Python 3.9 release. Exciting.

#

I think I'll do a compile today

undone hare
#

Generic type hinting is so cool

#

That's all I have to say

wide shuttle
#

The new parser is pretty cool, as in it can do more/different things

#

That python-ideas post from Guido received some criticism (the pseudo print statement one), but it's an interesting "proof of concept" to show what's now easily possible

#

And that's how I mainly read the message

undone hare
#

Being able to assert back and forth is quite handy yeah, I hope we'll some more funky grammar in the future

raven pike
#

What does this parser able to do compared to the old one? What's the highlight?

wide shuttle
#

I'm not qualified to try and give you a thorough explanation myself

undone hare
#

The whole thing is that an LL(1) parser will run all the possibilities sequencially, while the PEG will explore each layer horizontally before moving down. It means that PEG aren't context-free grammar and allow more things to be specified in the grammar rules including lookhead and lookbehind assertions. Python initially used the LL(1) parser outlined in the dragon book (from where I take all of those informations) which is a quite old book from the 80s, when every byte of memory mattered and so lookahead and lookbehind were just a no, because it used too much memory.

mint forge
#

who wants to play

unkempt rock
#

@mint forge nice

torpid narwhal
#

The subreddit on Pep 622 is gnawly.

undone hare
#

!pep 622

fallen slateBOT
#
**PEP 622 - Structural Pattern Matching**
Status

Draft

Python-Version

3.10

Created

23-Jun-2020

Type

Standards Track

undone hare
#

Right

#

That's understandable haha

daring siren
#

I'm starting a new project. How ready is 3.9?

wide shuttle
#

If you want to start an actual production project now, I'd not recommend starting with a beta version. There will still be support for Python 3.8 for over 4 years.

glass robin
#

Pep 622 would be for 3.10?

daring siren
#

Well, it's not a production thing but hey

#

If it's usable and kinda stable I'm all in

peak spoke
#

Useable is relative, since except some edge cases, libraries with binaries either won't support it or you'll have to compile them yourself hoping everything works

daring siren
#

Oki doke. Thanks

lost nexus
#

@glass robin

Python-Version
3.10

unkempt rock
#

how to upload the files to the onedrive using python?

#

please ping me.

boreal umbra
#

also, what exactly is a wheel?

noble latch
#

can the i in "for i in range()" be replaced with any other letter? and can %s in prints be replaced too?

cloud crypt
#

where?

#

if you are not using the variable while looping, consider writing for _ in range(...)

#

and yes you can totally use any valid identifier you wish

#

I don’t know why would you use %s for string formatting because f-strings are a better solution

brazen jacinth
#

Anyone ever gave a shot at writing their own version of the CPython interpreter?

cloud crypt
#

what do you mean under writing own version of CPython interpreter

brazen jacinth
#

i'll rephrase, your own interpreter for python

#

my thesis task is basicly to write a pyton interpreter using bytecode as it's direct input

cloud crypt
#

it’s a very large task to do

brazen jacinth
#

i am aware

#

then again it's basicly write the ceval part plus objects

#

i realise i won't be able to implement probably 90% of the functionality that cpython has to offer, and probably won't cover the 99% of the language spec

#

still, will probably offer great insight into the internals of python

#

im just wondering if anyone here attempted something like it

boreal umbra
#

@brazen jacinth I've forked cpython and messed around with it. PyPy and Jython are other implementations.

#

I think I read that cpython is smaller than the compiler for Java, but Java code makes more guarantees than Python code about what a given line does.

brazen jacinth
#

is that due to the fact that it's dynamic vs static, or are the differences bigger then merely that?

raven depot
#

How to make database?

#

On sql

glass robin
boreal umbra
#

@brazen jacinth I assume it has something to do with that. When you use the dot operator to access an attribute, it's not actually guaranteed that that object has that attribute, but it's not guaranteed that it doesn't have it either.

#

Even between instances of the same class, you could arbitrarily give one instance an attribute that another instance doesn't have.

#

!e

class A: pass
a = A()
a.thing = 'hi'
print(a.thing)
b = A()
print(b.thing)
fallen slateBOT
#

@boreal umbra :x: Your eval job has completed with return code 1.

001 | hi
002 | Traceback (most recent call last):
003 |   File "<string>", line 6, in <module>
004 | AttributeError: 'A' object has no attribute 'thing'
boreal umbra
#

Even when you know the type of an object, you're not even guaranteed to know what attributes it will have. But this is just a small part of the picture.

#

Looks like you can arbitrarily delete instance variables with del as well.

brazen jacinth
#

yea, interpreter and runtime overhead + constant type checking plus what you mentioned

#

definitely appreciate static types in some sense more given this info

#

i wonder if given mypy anotations basically everywhere, as in right in the implementation directly, would it help speed up common operations significantly

red solar
#

ooh yay c 🙂

#

can i ping you later in #c-extensions when i need help with implementing stuff like __index__ and whatnot for my classes?

boreal umbra
#

When datetime stores a datetime associated with a specific timezone, does it store it as utc internally and do conversions as needed?

#

I'm listening to the latest episode of talk python

#

If I have a datetime for 1pm in New York and 1pm in Chicago, I want subtracting Chicago from New York to give me a time delta of one hour, not zero.

#

Not sure which it does.

visual trout
#

wait can i append to a list by doing list += "a" or whatever

peak spoke
#

that's synonymous with .extend

visual trout
#

and .append right?

boreal umbra
#

@visual trout there's no operator for appending to a list.

solemn jewel
#

.append is only for a single object

#

at least i think so

boreal umbra
#

You're right @solemn jewel

spice pecan
#

.append is a single object, .extend is all objects from an iterable

boreal umbra
#

You can even append a list object to list, but then the list itself is an element

#

Whereas extend joins the lists

visual trout
#

so if i have say this list list_ = [1, 2, 3]
i can't do list_ += 4?

#

and then list_ is now 1, 2, 3, 4

boreal umbra
#

Nope

flat gazelle
#

you cannot indeed

spice pecan
#

no, but you can do list_ += [4]

wide shuttle
#

No, you can't do that; the inplace add is for extending a list with iterables, yeah

visual trout
#

oh!

#

thanks!

boreal umbra
#

I've been meaning to implement my own list class where << is append

#

Which idea came from another helper.

spice pecan
#

You can also do list_ += 4,, which will create a tuple with 4 as its only element (due to the trailing ,), but surrounding the item with [] is way more readable imo

wide shuttle
#

@boreal umbra Should be trivial if you subclass UserList

boreal umbra
#

Yeah

#

The same helper said something about implementing the bitshift operators for deque

visual trout
#
for i in prefixes:  prefixes += [i.upper()]```
boreal umbra
#

I'd ping the ones who I think it was but I don't want to disturb them.

wide shuttle
#

Yeah, salt gets crazy

visual trout
#

so i can do this right?

peak spoke
#

Stelercus from the code, sub does base + otoff - myoff where base is a timedelta where everything's subtracted and the offs are offsets

visual trout
#

so that my list has one version in lower case and one in upper?

spice pecan
#

it'd be better to just use prefixes.append(i.upper())

visual trout
#
  File "Backtick.py", line 10, in <module>
    for i in prefixes:  prefixes += [i.upper()]
MemoryError```
#

turns out it didn't work

#

but yeah, thanks!

boreal umbra
#

@peak spoke I didn't understand that too well but I'll look at the code next time I'm at my computer

#

@visual trout that's a memory error

visual trout
#

how come i got it

#

isn't it completely fine code?

boreal umbra
#

What is prefixes?

visual trout
#
  File "Backtick.py", line 10, in <module>
    for i in prefixes:  prefixes.append(i.upper())
MemoryError```
peak spoke
#

No, you have infinite iteration

visual trout
#

a list with strings

boreal umbra
#

Is it some huge thing?

visual trout
#

3 strings to be precise lol

peak spoke
#

for each item in prefixes you add an another prefix

visual trout
#

prefixes = ["c#", "js", "py"]

#

oh right

#

i know how to fix that tho

#

one sec

#

damn feedback loops

spice pecan
#

iterate over a copy

boreal umbra
#

Oh right

#

You usually don't want to modify the container you're iterating over.

visual trout
#

for i in len(prefixes): prefixes.append(prefixes[i].upper())

#

fixed it

boreal umbra
#

That won't work, I don't think

peak spoke
spice pecan
#

for i in prefixes[:] or for i in prefixes.copy()

#

And you have to use range(len(prefixes)) instead of just len(prefixes), if you're going the indexing route

boreal umbra
#

You could just do [e.upper() for e in prefixes]

visual trout
#

just fixed it after getting that error yes

#

i'm tired :(

#

AHA!

#

there we go

peak spoke
#

So assuming new york and chicago aren't the same timezone then the output != 0

visual trout
#

thanks guys

spice pecan
#

yeah, something like prefixes.extend([e.upper() for e in prefixes]) should be more elegant

boreal umbra
#

Iterating over a range of numbers and then subscripting the container you really care about usually isn't the way to go.

visual trout
#

so you're saying i'm doing it wrong?

flat gazelle
#

I would honestly just check with .lower() rather than adding both copies

boreal umbra
#

Sorry @visual trout, do you feel that I've offended you?

visual trout
#

no no

#

i was just joking

#

i really appreciate the help, i truly do

#

prefixes.extend([e.upper() for e in prefixes])

#

soooo

#

this piece of code then (not mine)

boreal umbra
#

Would you like to dissect why that code works?

visual trout
#

can i do my best to try and explain it first?

boreal umbra
#

Yes, that would be great.

visual trout
#

[e.upper() for e in prefixes]

#

this part creates a separate list of my list but in uppercase

#

and the .extend just adds it to my original list?

boreal umbra
#

Yes, that's exactly right

visual trout
#

and this is better because i'm not editing my list as i'm looping through it

#

right?

boreal umbra
#

Right

#

The list comprehension, which is the little for loop like part, gets evaluated first.

#

And it's making a separate list based on the first one

#

The first one isn't changed during that process.

visual trout
#

sounds clever

#

e.upper() for e in prefixes

#

this piece of code

#

what is that "thing" called

#

like

boreal umbra
#

A list comprehension

shy belfry
#

List comprehension?

visual trout
#

oh

#

i'm gonna have to read up on that

#

see

#

i only started actually investing time into python and stuff a month or two ago, and stuff like this really helps

#

people that actually stop to explain

boreal umbra
#

They're one of the most elegant features of python, in my opinion

visual trout
#

thanks for you time!

boreal umbra
#

Other languages use them too

#

Apparently

#

I just assumed Guido invented them.

flat gazelle
#

they come from haskell afaik

shy belfry
#

Well, isn't the closest to comprehensions in Js a combination of filters and maps?

boreal umbra
visual trout
#
    h_letters.append(letter)

h_letters = [ letter for letter in 'human' ]```
shy belfry
#

If I'm not mistaken the comprehensions are somewhat unique to Python when it comes to the modern and well known languages.

visual trout
#

yeah i thought it was gonna be a small talk thing

#

but it ended up being a thread of comments

#

thats my bad

boreal umbra
#

@visual trout you could do that even more quickly with list()

visual trout
#

this is an example i found online actually

flat gazelle
#

julia, haxe, C# (if you consider LINQ), Haskell all have comprehensions

visual trout
#

two different ways to do it

flat gazelle
#

and probably other langs I forgot about.

shy belfry
#

julia, haxe, C# (if you consider LINQ), Haskell all have comprehensions
@flat gazelle LINQ too is kind of just a clunky way of combining maps and filters into one function.

visual trout
#

can i do list(letter for letter in 'human') instead of [letter for letter in 'human']

boreal umbra
#

!e

bob = 'bob'
print(list(bob))
fallen slateBOT
#

@boreal umbra :white_check_mark: Your eval job has completed with return code 0.

['b', 'o', 'b']
shy belfry
#

Just list('human').

visual trout
#

oh right

shy belfry
#

Seems less readable to me.

boreal umbra
#

list is the class that lists belong to, but when you call it like a function, it converts that thing to a list, as long as it's an iterable.

flat gazelle
#

ye, unpacking into literals is rarely used

visual trout
#

letter for letter in 'human' why is the index variable name thing being typed twice

clever escarp
#

usually you want to be modifying something in a comprehension, but you can also use comprehensions for filtering passing_grades = [grade for grade in range(101) if grade >= 60]

boreal umbra
#

for letter is where you define a variable name

#

Like in a regular for loop

visual trout
#

yes

boreal umbra
#

The part before that is what you do to it.

visual trout
#

like for i or so?

boreal umbra
#

Before we called upper on the instance

#

But this time you didn't do anything to it.

visual trout
#

ooooh

shy belfry
#

Imagine you're iterating just like you usually would, so for letter in "humans" is how to iterate, and then in the front part you're selecting that value and you could even do something like upper(letter) if you wanted to.

visual trout
#

so it could be letter.upper() for letter in "Hello World"

#

or whatever

boreal umbra
#

Yeah it could

shy belfry
#

Exactly!

visual trout
#

gotcha gotcha

#

list comprehension

#

good to know about

boreal umbra
#

It also works for sets

visual trout
#

thanks guys, i'm gonna go to bed now :>

#

dunno what sets are, not even gonna ask today lol

boreal umbra
#

And any collection that can accumulate from an iterable

#

And dictionaries. But that's a bit different

visual trout
#

wait it's another datatype!?

shy belfry
#

Mind explaining what tuples are while we're at it?

boreal umbra
#

Sets are a data type

shy belfry
#

And how they differ from lists. 😅

boreal umbra
#

@shy belfry tuples? Sure.

visual trout
#

wait

#

what determines which order they pop up

boreal umbra
#

Do you understand mutability?

visual trout
#

it's different every time...?

#

uh, short answer, no

#

oh you mean in the sense of not being able to change?

#

like a tuple

boreal umbra
#

I was asking Dan6erbond

visual trout
#

nvm

boreal umbra
#

You can sleep 👌

visual trout
#

a tuple is immutable right?

boreal umbra
#

If you want

visual trout
#

before i go

boreal umbra
#

Yes

visual trout
#

it can't change it's order

#

got it

boreal umbra
#

It's also hashable

visual trout
#

you might see me around some other day

shy belfry
#

Do you understand mutability?
@boreal umbra yeah pretty well from the C#/Java context.

visual trout
#

have a good day/night or whatever

#

bye!

boreal umbra
#

@shy belfry tuples are immutable

shy belfry
#

Night!

#

Oh that's it?

boreal umbra
#

Once you make a tuple you can't add, remove, or change elements

#

The best you can do is make a new tuple with the change you needed to make

shy belfry
#

That makes sense! Is it also more efficient to use tuples in that case?

boreal umbra
#

Don't worry too much about efficiency at that level.

#

If using tuples makes your code harder to read than using lists, it's probably not worth it.

shy belfry
#

Yeah I figured that to be the case as well. I was mainly asking because at some point in my code I was copying a tuple's values into a list with comprehension, it never changes, because I needed to get a specific attribute.

boreal umbra
#

Well, if you have a tuple, you can convert it to a list with list()

#

No list comp needed.

#

But this has an O(n) runtime

#

I think

shy belfry
#

Oh I still needed to do the comprehensions because I was doing [self.getval(item) for item in args]. Haha.

boreal umbra
#

Aha

shy belfry
#

I wrote a tiny reactive framework to manage callbacks when values are changed, since Python has all these descriptors.

#

Those were another incredibly weird concept from what I'm used to with C#. Even the custom getters and setters don't compare. 😅

boreal umbra
#

Do people have getters and setters with method syntax in C#?

#

Because I really hate those.

flat gazelle
#

they have something similar to @property

boreal umbra
#

Yay

shy belfry
#

Yeah C# lets you define custom getters and setters just below the variable declaration. Unlike Java and that crap. Kotlin does that, too.

raven pike
#

Hey guys

#

Do @cache holds recent x values or first x values?

#

i mean lrucache i guess?

spark magnet
#

@raven pike lru stands for Least Recently Used, which are the things discarded.

#

so it keeps the values that have been used recently (not the ones added recently)

mystic rain
#

Hello guys, could any one you recommend me any "List of programs to do while learning python" kind of thing, since i heard its better to learn while doing projects, and not by learning by the book

magic python
mystic rain
#

do i ask there?

#

@magic python

magic python
#

yes

boreal umbra
#

@magic python while one could ask that in python-general, there's actually a !resources command

#

!resources

fallen slateBOT
#
Resources

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

boreal umbra
#

so you can pull that one out any time

magic python
brave badger
#

That PEP provides the typing module while mypy utilizes it for checking the types

raven ridge
#

and PEP 484 defines the format of the type annotations that mypy requires to work.

magic python
#

does mypy build off of this then? Is this a relationship similar to attrs and dataclass, where a lot of attrs features were pulled in for dataclass? or not 🤔

brave badger
#

Not necessarily, all that mypy does is provide static type-checking but not actual classes for typing iirc

magic python
#

is it considered best practice to use typing? I'm a bit confused, i've used arguments such as

def f(x,y,z=False)

before, where z doesn't have to be passed... but i'm looking at pandas source and see xlabel: Optional[Label] = None, which seems a bit clearer that this is optional...

But - there's also ax = None, and this is also optional... why not have ax: Optional[matplotlib.axes] = None here?

I don't understand properly why there are some optional arguments which have Optional[...], and some that don't

raven ridge
#

PEP 484 defines the protocol for representing type annotations, and mypy uses it.

#

I don't understand properly why there are some optional arguments which have Optional[...], and some that don't
@magic python because type hints are only a few years old, lots of code predates them, and adding them to existing code is a non-trivial amount of work

magic python
#

oh ok, i didn't consider that. Why isn't it simply a case of adding the Optional as there are in others? I assume there's more going on, i just don't get why that'd be much more than a search and replace at the mo

raven ridge
#

Optional takes an argument in the [] - you need to read the code or the docs to figure out what argument that should be

magic python
#

ah, yeah... Is this the sort of thing that languages like Java or whatever are able to do more easily?

#

because of explicit types and stuff? Or is this just generally tricky

#

(i'm referring to the refactoring)

raven ridge
#

In Java you must always provide the type - so, it's not easier, but it's required that you figure it out when the code is first written.

#

Needing to go back and add it after the fact is a problem unique to Python.

magic python
#

interesting... i've only recently been bumping into these kinda things tbh, what i'd consider more software enginnering things rather than writing a script, getting the data, and running away.

narrow kettle
#

static langs make the world go round

magic python
#

they seemed clunky, but now i get why people would like them... i guess in a couple of years things will be much more robust (in python) with typing and stuff used overall? 🤔

narrow kettle
#

they are SAFE

#

and its hard to appreciate that if you havent worked on large scale projects

north root
#

indeed

#

i've been doing some rust, and i love it

#

it's so safe

narrow kettle
#

im a c# dev

red solar
lost nexus
#

god yes i love rust

magic python
#

yeah, i can get some of that - i only recently found out about * in functions and i really like that it actually enforces something 😄

narrow kettle
#

which is obviously a static lang

red solar
#

is C# any fun? always wanted to try it, but i'm not a huge fan of java

narrow kettle
#

when i write python i miss c# intellisense SO much

#

im a huge fan of c#

#

its a great lang

red solar
#

but would i like it even though java is meh?

narrow kettle
#

i hate java

red solar
#

also yeah that's pretty cool feature 🙂

#

oh ok good lol

north root
#

as do i

narrow kettle
#

java is miserable to write

#

c# is excellent to write, for many reasons

boreal umbra
#

Java makes me question my will to live.

magic python
#

i'm mainly in pandas tbh, so I'm not sure c# or rust could really replace, the only other is R... but python is better for production already... so I guess I'm stuck with python

red solar
#

glad we're in agreement 😂

narrow kettle
#

c# is java, if you took out all the dumb shit like checked exceptions and added a fuck ton of cool stuff on top

north root
#

we're all java haters, woohoo

narrow kettle
#

can i drop the c# invite? or will the bot shout at me

north root
#

it's whitelisted

narrow kettle
#

a lot of us hang out here

boreal umbra
#

My pretentious friend liked Java, but then he realized that rEaL pRoGrAmErS write everything in C

#

so now he likes C

magic python
#

I've heard nice things about rust... but the ecosystem for R and python is so good for data stuff.

#

maybe i'll just learn typing and mypy 😅

narrow kettle
#

the worst part of rust are the people who code in rust

north root
#

lol

boreal umbra
#

I really hate the name of mypy

red solar
#

C is awesome if you use it in contexts where you don't need to worry about error handling or cleanup 🙂 (like python extensions since the runtime handles it)

magic python
#

ourpy 🛠️

north root
#

Python feels so free, but that comes at a cost of course

red solar
#

lmao

narrow kettle
#

tbh i miss static types alot when writing my discord.py bot

#

im so used to coding with intellisense

red solar
#

do you not find type hints make up for it mostly?

narrow kettle
#

where the ide just pops up all teh possible options

#

not really

magic python
#

doesn't pycharm do that?

narrow kettle
#

it can help

red solar
#

pycharm seems to do a pretty good job for me

#

seems somewhat comparable to what clion can provide

#

and clion's awesome

north root
#

vs code does pretty well too

narrow kettle
#

pythons dynamic nature means it just cant, cuz it doesnt know things will be

north root
#

clion is great

narrow kettle
#

its ok

magic python
#

vscode completion is pretty poor imo

boreal umbra
#

does PyCharm have its own linter?

narrow kettle
#

but its not like C# and VS

boreal umbra
#

or does it use mypy?

narrow kettle
#

not even clse

north root
#

that's true

magic python
#

i find vsc is really slow, and it doesn't fuzzy match substrings etc

#

i often have to hit ctrl + space to give it a prod

narrow kettle
#

c# even has an ai feature that will train itself on your codebase and suggest ur most likely match

magic python
#

there's a thing for that you can use in python or something, i forgot ( kite? )

narrow kettle
#

its pretty useful, tho some people dont like it

red solar
#

ehhh - is that really a place where we need ai tho?

#

yeah kite

narrow kettle
#

NEED?

#

no

#

but it does come in handy

red solar
#

hmm ok team completions looks cool

magic python
#

i'd like something better than vsc, i had a look at pylance and that didn't seem to do much either

red solar
#

i'll be honest, i never felt that intellisense outperformed whatever clion has (some clangd thing?)

narrow kettle
#

i jsut installed pylance

magic python
#

didn't seem to make any diff for me

narrow kettle
#

you have to turn it on

#

tho some new features are cool

#

unused imports are nice

#

and auto import

magic python
#

🤔 i thought i had

#

unused imports are covered by autopep tho aren't they

narrow kettle
magic python
#

i think , i can't remember what it is.... whether there's some pre-commit thing for it

red solar
#

swear pycharm already does all this tho

narrow kettle
magic python
red solar
#

like seriously try it out

narrow kettle
#

vsc is working fine for me rn, tho i use rider for c# sometimes

north root
#

i have pycharm pro but i've used it like once lol

magic python
#

flake8 already highlights unused imports though

narrow kettle
#

i have no aversion to pycharm i just dont need it

#

and i like the look of vsc

north root
#

yeah, i like vsc better

narrow kettle
#

flake8 already highlights unused imports though
it doesnt grey out unused code

red solar
#

ah, i'm used to jetbrains

narrow kettle
#

im using flake8 inconjunction rn

#

ya i really like rider for non windows c# dev

magic python
#

no it gives it wiggles and if you have errorlens installed you'll get a big bar

narrow kettle
#

IDEA is a great platform

raven ridge
narrow kettle
#

WITH vim binds oc

#

cant live without vim binds

magic python
#

yeah i use vim keys in vsc... they're OK... i feel it might slow it down a lot though

red solar
narrow kettle
#

like slowed down the editor?

magic python
#

it doesn't? I was wondering if that's why my completion is crap

narrow kettle
#

its a very light weight plugin lol

#

it doesnt slow anything down

magic python
#

well idk then, maybe vsc is a bit crap i guess

narrow kettle
#

well maybe YOU if your not a vim person

#

but the editor is fine

magic python
#

vim keys aren't vim imo

narrow kettle
#

vim binds are lmao

magic python
#

🤷‍♂️

narrow kettle
#

vim binds are the key draw of vim

magic python
#

I wouldn't say i'm a vim person, but i use vim keys everyday

raven ridge
#

This is all way off topic for this channel

boreal umbra
#

super objects

#

I don't really get what they are.

raven ridge
#

super() is shorthand for super(ClassDefiningThisMethod, self)

red solar
#

and it's beautiful, especially when you inherit from multiple classes 🙂

raven ridge
#

And what it returns is a proxy object such that any method or attribute accessed on it will come from the a class that's after ClassDefiningThisMethod in self.__mro__

boreal umbra
#

how does it work as a shorthand? Does the parser just handle it in a special way?

raven ridge
#

I think so

boreal umbra
#

interesting

#

so does it implement __getattr__ in a special way that intelligently searches the mro?

raven ridge
#

And yes, the proxy object that is returned when you call super has a getattr that looks at the mro of the object it was bound to, and skips over classes before the specified one.

#

and it leverages the descriptor protocol to pull that off, I believe.

boreal umbra
#

I'm reading through the PEP, but I wonder, if super() was going to get special treatment by the parser anyway, why require the parens?

raven ridge
#

it was already a function, and there's still valid use cases for calling the two arg form (mostly backwards compatibility, but it could potentially be useful even without that)

boreal umbra
#

I like the look of super.__init__() better.

raven ridge
#

so, making it both a function and an always-available implicit variable seems like it'd be unduly confusing.

#

that'd be a lot more magical, too. when you see super().__init__(), it's clear that super is a built-in function that returns something to you - that's not at all clear in super.__init__()

boreal umbra
#

I've always thought super().__init__() was confusing, so that apparently wasn't solved 😛

raven ridge
#

I think the two arg form was a lot clearer and less magical, but also far more verbose, so... 🤷

spark magnet
#

people often got the two-arg form wrong.

raven ridge
#

the order of the two arguments?

spark magnet
#

they put the parent class instead of their own class

boreal umbra
#

I remember someone was doing an exercise where they had to make a Mom and Dad class and inherit from both

spark magnet
#

because they think they have to invoke the method on the parent

red solar
#

it's understandable

raven ridge
#

ah. yeah - but that's a total misunderstanding of what super does.

boreal umbra
#

I ended up advising them to do Mom.__init__(self, ...) and Dad.__init__(self, ...)

spark magnet
#

@boreal umbra ick

boreal umbra
#

also both __init__s had different signatures.

raven ridge
#

an understandable misunderstanding, because super has a terrible name, but...

#

people who are familiar with the concept of super from another language will have absolutely no idea what super does in Python, and that seems... less than ideal. Because it doesn't call something on the superclass, not necessarily. It calls something on another class, which may be a sibling class instead of a parent class.

boreal umbra
#

@spark magnet I'm not sure how else they could have finished the assignment because the Mom and Dad class were neither subclasses of the other, and their __init__s weren't the same, though I don't like the way the assignment was designed.

spark magnet
#

@boreal umbra yeah, that seeems like a bad exercise

raven ridge
#

Python's multiple inheritance is cooperative. Every class participating in multiple inheritance needs to have been designed to support it, in order for it to work properly.

#

even if a class thinks it has no base classes, it needs to call super(), for instance.

boreal umbra
#

why

red solar
#

yeah what?

raven ridge
#

because super delegates to the next class in the MRO, not just to the superclass, and the next class in the MRO might be a sibling class, rather than a parent class.

boreal umbra
#

maybe I misunderstood. I thought you were talking about classes that inherit only from object

raven ridge
#

I am.

red solar
#

how do the classes that can't be inherited from work?

spark magnet
#

@boreal umbra it's a common misunderstanding to think that because you know what you derived from, that you know where super() will go.

raven ridge
#

you've got two classes A and B that inherit only from object. Now you make a class C that inherits from both A and B. C calls super().__init(...) to initialize A. If A doesn't call super().__init__(), then B never gets initialized.

boreal umbra
#

how would the call to super() made in A.__init__ know to go to B.__init__?

spark magnet
#

@boreal umbra because it has self, and it can see that the MRO has A and then B

boreal umbra
#

I see

#

So the sequence of classes to visit for __init__ing is more like a linked list than a queue?

#

this is a very tenuous comparison

#

let me think of a better way of explaining it.

#

So the call super().__init__(self, ...) only guarantees that one more call to a method named __init__ will occur, yes?

raven ridge
#
In [82]: class A:
    ...:     pass
    ...: 

In [83]: class B:
    ...:     pass
    ...: 

In [84]: class C(A, B):
    ...:     pass
    ...: 

In [85]: C.__mro__
Out[85]: (__main__.C, __main__.A, __main__.B, object)
north root
#

dang it i was about to show that lol

#

you're too fast

boreal umbra
#

I'm familiar with MROs

raven ridge
#

super() takes 2 arguments - a class, and an instance. It skips over all the classes in the instance's MRO before the specified class, and then looks up the given attribute on the next one after the specified class.

boreal umbra
#

So unless you're sure that a given class inheriting only from object won't be used in a multiple-subclassing situation, you have to include super().__init__(self, ...) to ensure that it keeps searching the MRO for sibling classes that ended up further back in the MRO?

#

it won't automatically "queue" those calls for sibling classes?

raven ridge
#

yes, if a class wants to behave properly in a multiple-inheritance scenario, it must call super(). Multiply inheriting from one that doesn't can do the wrong thing.

boreal umbra
#

fascinating. Thanks for explaining that

raven ridge
boreal umbra
#

No one can explain it better than you lemon_hyperpleased

glad radish
#

So, I have a string ("7.50") and i am converting it to a float (float("7.50")) but it makes it look like 7.5 rather than 7.50
How do I make it show the trailing 0?

shy belfry
flat gazelle
#

floats cannot store that trailing zero, so you have to keep it in string form or convert it t string with 2 decimal spaces

shy belfry
#

I think this is what you want: '{:.2f}'.format(3.141592653589793)

#

!e

print('{:.2f}'.format(3.141592653589793))
fallen slateBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

flat gazelle
#

probably better to do format(3.1415, '.2f')

glad radish
#

Thank you guys 😄

shy belfry
#

probably better to do format(3.1415, '.2f')
@flat gazelle hmm, true, that's a bit more readable!

#

I forgot about the format builtin.

shy belfry
#

Is there a way to return a value, and add extra functionality to it? At the moment I'm creating a class that inherits from the previous type, and adding those methods I need, but this doesn't work for bool and NoneType unfortunately.

sterile kernel
#

Well, you could look into decorators

#

That would allow you to customize the return value of a function

shy belfry
#

I think I might be explaining this wrong... What I'm trying to do is let's say I have the boolean value True that I want to return. But I also want the user to do this:

val = get_value() 
# >>> True
val.method
# >>> custom method
sterile kernel
#

oh, you want the user to take additionnal steps after getting their returned object ?

shy belfry
#

Precisely, more specifically what I'm trying to do is work with advanced descriptor functionality:

def __get__(self, instance: Any, owner: Any):
    class ObservableProperty(type(self.value)):
        name = self.name
        history = self.history
        on_change = self.on_change
    return ObservableProperty(self.value)
sterile kernel
#

defining a class inside a method… pretty harcore ! 😄

#

Well, ok, and what should the user do after getting their ObservableProperty ?

shy belfry
#

Haha! Yeah, it sure is. I've been trying to muck around with all these crazy features Python offers to create ReactiveOwners... I already published a version of the library that works, but it's only functional with types that aren't None or bool.

#

Well, ok, and what should the user do after getting their ObservableProperty ?
@sterile kernel here's an example from my tests:

self.test_class.name.on_change(call_change_name)
self.test_class.name = "Bar"```
#

You can access, set and of course use the extended functionality from that variable.

sterile kernel
#

I don't get the problem… Doesn't it work as-is already ?
Furthermore, nothing (get/set value) is mandatory, is it ? So you really don't need to do anything…

shy belfry
#

This unfortunately doesn't work for bool and None, no. :/

#

For everything else it does seem to, though!

#

But bool and None are "final" in Python.

#

At the moment I just raise errors when a user uses those.

#

But it's not that great because bool in particular should be reactive.

sterile kernel
#

Maybe, it's because bool and None are singletons, yeah
There's only ever a single instance of None, and there's no point in setting it to another value.

shy belfry
#

Exactly... So there's no way to cleanly do what I want?

#

I'll probably have to add some if/else statements along the lines then.

sterile kernel
#

I don't see any way, no…

shy belfry
#

Alright, thanks for the help anyway! 🙂

sterile kernel
#

no problem ;p

undone hare
#

Tbf python isn't built to do this sort of things

shy belfry
#

Python is the only language I've managed to do this kind of crazy stuff with descriptors in the first place, though. :P

#

Those inline-classes inheriting from dynamic types... Feels horrible coming from other languages.

#

But it's enabled neat functionality.

undone hare
#

The issue is that you want to have a sort of enriched object, but you would still have some quirk, because it can't technically be the same object

#

For instance, the ID would be different, which is an issue for everything that relies on hashing, like dicts

shy belfry
#

True... I haven't even thought too hard about those things because my use-case for this library doesn't really requires those features to work...

mint forge
#

how much space is required for the download of -python

undone hare
#

The source code is around 30Mb, it should be less for the compiled version

#

42Kb for the main executable according to snekbox

unkempt rock
#

i think pep563 "Postponed Evaluation of Annotations" just saved me

#
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from connection import ApiConnection
``` is this the accepted way of avoiding circular dependencies when typehinting, then?
shy belfry
#

Yep.

#

That's pretty much the reason it's been introduced.

#

I use it consistently with aPRAW.

unkempt rock
#

i spent way too long looking for a solution for that in the internet

shy belfry
#

Hahaha. Took me a while to understand what's going on, too.

true hollow
#

Is there a way to create an empty class? If you create an instance of object (the most basic class), it will already have __init__, __init_subclass__, __del__, __delattr__ and more, but I don't want nothing, nor methods nor attributes

cloud crypt
#

you would need to recreate type and object from scratch then or something

true hollow
#

:|

cloud crypt
#

or bypass their stuff

true hollow
#

damn i never though this was going to be soo hard lol

peak spoke
#

Why would you need that?

true hollow
#

idk
yesterday i lost access to internet and i was bored, so i was playing with python

#

then i did some js

#

and then it came to my mind when i was practicing js classes: "is there a way to create an empty class using python?"

flat gazelle
#

pretty sure you always need at least a __class__

true hollow
#

python is a different story peperelief

#

also hey
you're a helper
congrats 😄

flat gazelle
#

thanks

cloud crypt
#

congrats owoAyaya

true hollow
#

im still stuck with developer blobSweat

#

well

#

so

#

no way to create an empty class unless you do some fuckery on the python core, right?

flat gazelle
#

even with core fuckery

peak spoke
#

I think a python2 old style class is a bit more barebones

undone hare
#

What about type("ClassName", (), {})?

true hollow
#

uh what?

undone hare
#

!d type

fallen slateBOT
#
class type(object)``````py
class type(name, bases, dict)```
With one argument, return the type of an *object*. The return value is a type object and generally the same object as returned by [`object.__class__`](stdtypes.html#instance.__class__ "instance.__class__").

The [`isinstance()`](#isinstance "isinstance") built-in function is recommended for testing the type of an object, because it takes subclasses into account.... [read more](https://docs.python.org/3/library/functions.html#type)
undone hare
#

See the second part

flat gazelle
#

that is not an empty class

peak spoke
#

It's the same as doing class ClassName: pass

true hollow
#

i always thought type is a function

undone hare
#

Maybe I misread the question, but it does create an empty class inheriting from object at runtime

spark magnet
#

@true hollow i don't think you can do what you want.

visual trout
#

what is the easiest way to turn any number into an x digit number?

radiant fulcrum
#

int()

visual trout
#

no

#

like

#

turn 1 into 001

#

or 32 to 032

#

because i know how i could do it

#

but it would be very not efficient is my guess

radiant fulcrum
#
my_int = str(my_int)
res = "000"[:-len(my_int)] + my_int

ig this would work

sturdy timber
#

f-strings would probably be easiest, e.g. print(f'{3:03}')

radiant fulcrum
#

lmao forgot they existed

visual trout
#

what does the f do?

radiant fulcrum
#

just another method of string formatting

sturdy timber
#

Although this probably isn't the right channel for that sort of question

visual trout
#

my bad

radiant fulcrum
#

like:
"{}".format(x)
f strings are like
f"{x}"

visual trout
#

but what does the f prefix do?

radiant fulcrum
#

formats

visual trout
#

ah

#

gotcha

#

so if i for example tell python to write my single digit but i want it to be 3 digits, it just adds 2 zeros?

radiant fulcrum
#

no iirc

visual trout
#

iirc?

#

just looked it up

#

go on

radiant fulcrum
visual trout
#

f'{3:03}'

#

no this works just fine

radiant fulcrum
#

ah nice

visual trout
#

@sturdy timber mind explaining or no?

sturdy timber
visual trout
#

alright

visual trout
#

turns out str.zfill(int) is by far the easiest and most readable way to do it

shy belfry
#

You can do a lot more with f-strings / format() regarding floats, decimal points, datetimes, padding etc.

boreal umbra
#

Yesterday we were talking about how super() is a special case for the parser. On a related note, having class methods for special constructions seems like a popular solution for the fact that Python doesn't let you overload __init__

#

And typically those class methods do some extra work and then pass some variables to cls()

#

But what if there's no straightforward way to take the inputs for that class method and create an instance in terms of __init__s signature

near coral
#

anyone leveraging PEP 617 yet?

boreal umbra
#

You could create the instance manually with super().__new__(cls) and set the variables manually but I imagine circumventing __init__ has unforseen consequences.

near coral
#

keeping up with Python updates is overwhelming

true ridge
peak spoke
#

Does that mean I can throw away \ from valid uses in normal cases?

near coral
#

so the bug is still out there?

#

looks like they closed it

true ridge
#

so the bug is still out there?
@near coral nop, it is allowed in 3.9 but only in the new parser and it will be part of the language spec on 3.10.

#

Does that mean I can throw away \ from valid uses in normal cases?
@peak spoke yea, there are no need for it from now on (3.10+)

near coral
#

thanks

#

great info

#

wait, they are getting read of the \ for line continuation?

true ridge
#

I mean for this case

near coral
#

oh ok

#

so much to learn

#

do any of you use 3.9 beta yet?

shy belfry
#

Yesterday we were talking about how super() is a special case for the parser. On a related note, having class methods for special constructions seems like a popular solution for the fact that Python doesn't let you overload __init__
@boreal umbra I'm not sure I exactly get what you mean here... but you can do this in Python to "overload" __init__:```python
def init(self, reddit: 'Reddit', data: Dict, submission: 'Submission' = None,
author: Redditor = None, subreddit: Subreddit = None, replies: List['Comment'] = None):
aPRAWBase.init(self, reddit, data, reddit.comment_kind)
AuthorMixin.init(self, author)
SubredditMixin.init(self, subreddit)

boreal umbra
#

@shy belfry I don't really like having that many if statements

#

Well, that's not what you're referring to

shy belfry
#

Where's an if-statement?

boreal umbra
#

I was thinking of something else for some reason

#

This looks more like inheritance?

shy belfry
#

Yes, this is inheritance. That's the thing - I'm not sure I get what you're saying about the overloading of __init__? Do you mean really like just overloading functions in general?

boreal umbra
#

Having multiple ways to create instances.

#

For example

#

I worked on a library where a certain class was meant to read data from a text file. It would store that data as a list of tuples.

#

So the __init__ method took a path to the file it was meant to represent

#

But there were a few times where you'd make the list manually and then wrap it in that class

#

So the __init__ method was changed to type check what it passed to it and just accept the list as an instance variable if it was a list, or read a file and create the list if it's a string/PathLike

#

So in retrospect, I would have rather had a class method for whichever of those two cases we'd decide is the odd one out.

shy belfry
#

Oh, yeah... I have to deal with that crap in apraw.Reddit, too. I just use a ton of if-statements. I like how Kotlin and C# support both overloads and default values.

boreal umbra
#

It doesn't make a whole lot of sense for Python to support overloading since the signatures are untyped

#
class A:
    
    def __init__(self, one, two):
        self.one = weird_func_one(one)
        self.two = weird_func_two(two)

    @classmethod
    def special_case(cls, special_value):
        """Never calls A.__init__ :O"""
        new_obj = super().__new__(cls):
        new_obj.one, new_obj.two = weird_function_three(special_value)
        return new_obj
#

It could be argued that A.__init__ shouldn't be written that way

#

this is just an example. We'll assume that there's some case where it makes sense for A.__init__ to be that way

#

So what I'm wondering is, what issues could arise by totally circumventing the init?

open trout
#

I didn't really look into the discussion, but I see no reason to support overloading simply because of A) the nimble use of *args and **kwargs in the language and B) classmethod constructors

boreal umbra
#

@open trout I'm specifically interested in classmethod constructors that, instead of converting their own arguments into values that can be passed to the __init__, totally circumvent __init__

open trout
#

Ah I see, but why would you want to circumvent it?

boreal umbra
#

in case someone ever thinks of a situation where trying to map the inputs to valid arguments for __init__ is inelegant.

unkempt rock
#

So __mro__ is literally just an inheritance path from the current class to object?

north root
#

yeah basically

unkempt rock
#

Oh sick I finally understood it 🙂

north root
#

!e

class A: pass

class B(A): pass

print(B.__mro__)
fallen slateBOT
#

@north root :white_check_mark: Your eval job has completed with return code 0.

(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
north root
#

it's just a tuple, starting with the current class and ending with object

unkempt rock
#

Can I overload mro with non class objects?

honest narwhal
#

so what are the new features coming to Python that everyone is so hyped about

brave badger
#

!pep 622

fallen slateBOT
#
**PEP 622 - Structural Pattern Matching**
Status

Draft

Python-Version

3.10

Created

23-Jun-2020

Type

Standards Track

brave badger
#

This primarily, and the new parser I think

boreal umbra
#

if I were to create a function metatype, how would I create instances of it?

#

I guess you could make a decorator that takes the __call__ attribute of the function and gives it to a function of the special metaclass?

raven ridge
#

What do you mean by "function metatype"? Can you better explain the problem you're looking to solve?

silk sorrel
#

what does -> do?

brazen jacinth
#

in C/PHP, attrib lookup, not sure it has a use in python?

open trout
#

Return type hinting

wide shuttle
#

@silk sorrel It's used in function annotations to annotate the return value

silk sorrel
#

That makes sense. Thank you!

brazen jacinth
#

oh right, type hints..

open trout
#

lol

#

you're forgiven, it's a pretty new thing after all

brazen jacinth
#

im using them more and more, but couldn't recollect the context here

open trout
#

back in my day people used docstrings 🧓

shy belfry
#

Speaking of docstrings...

#

What's the go-to for having decorators for classes and preserving __doc__ as well as __name__?

#

I doubt functools.wraps() will work in this case?

wide shuttle
#

What's your decorator returning? A new class object or a function object?

#

I don't think wraps works when applied to a type instance (class object), but it should work for a new function

shy belfry
#

A new class. A wrapper class to be specific that inherits from the given class and just adds some extra functionality. 😄

wide shuttle
#

Hmm

#

Interesting

#

Not sure how to best approach this. You could get it to work with the type constructor, but that's a bit less readable

#

!e

def decorator(cls):
    def other_method(self):
        print(f"The other method was called on {self}")

    new_cls = type(cls.__name__, (cls,), {"other_method": other_method})
    new_cls.__doc__ = cls.__doc__
    return new_cls


@decorator
class Foo:
    """This is a nice docstring!"""

    def method(self):
        print(f"Called method on {self}")


print(Foo.__doc__)
print(Foo.__mro__)

f = Foo()
f.method()
f.other_method()
fallen slateBOT
#

@wide shuttle :white_check_mark: Your eval job has completed with return code 0.

001 | This is a nice docstring!
002 | (<class '__main__.Foo'>, <class '__main__.Foo'>, <class 'object'>)
003 | Called method on <__main__.Foo object at 0x7f19643d30a0>
004 | The other method was called on <__main__.Foo object at 0x7f19643d30a0>
wide shuttle
#

Is there any reason for "delaying the inheritance" by using a decorator?

#

Also, this probably reverses the MRO (it places the additional class before the original class), so not ideal

brazen jacinth
#

adding funtionality

#

perhaps a mixin?

wide shuttle
#

Yeah, but why not just have an inheritance/mixin structure?

shy belfry
#

Hmm... I suppose it's because I want to make my library as easy as possible to use and I feel a mixin could have weird side-effects.

#

What I'm trying to achieve is this:```python
from reactive import all_reactive

@all_reactive
class Foo:
def init(self):
super().init()
self.name = "Foo"```

#

So the decorator looks like this:```python
def all_reactive(org_cls=None, only_type=None, not_type=None):
if org_cls:
class AllReactive(org_cls, ReactiveOwner):
def init(self):
super().init()
self.__only_type = only_type
self.__not_type = not_type

        def __setattr__(self, name: str, value: Any):
            if not isinstance(value, ReactiveProperty) and not name.startswith("_"):
                if self.__only_type and not isinstance(value, self.__only_type):
                    return super().__setattr__(name, value)
                if self.__not_type and isinstance(value, self.__not_type):
                    return super().__setattr__(name, value)
                try:
                    value = ReactiveProperty(value, name)
                except TypeError:
                    pass
            return super().__setattr__(name, value)

    return AllReactive```
open trout
#

thinkmon out of curiosity, what does your lib do? And what does reactive/all_reactive do?

radiant fulcrum
#

why is that class in the function aswell tho?

open trout
#

oh yeah just noticed that, that's so trippy

radiant fulcrum
#

like that can be moved out side of that function and replaces with a __new__ method no?

shy belfry
#

thinkmon out of curiosity, what does your lib do? And what does reactive/all_reactive do?
@open trout oh I'm actually happy to show this off because I have no clue if it's any good, but I like the idea and was hoping for some feedback anyway! https://github.com/Dan6erbond/ReactivePy

#

oh yeah just noticed that, that's so trippy
@open trout I wasn't sure how to have the dynamic inheritance...

#

There's probably a ton I could do to optimize the codebase to be honest. :P

#

It's so far just a bunch of hacks put together in a so-called "library".

open trout
#

Wow, that sounds cool! Good luck with it!

ruby prairie
#

is there a python equivalent of javascript's module.exports?
i have to import a lot of stuff from a file and i don't feel this is right

brazen jacinth
#

oh, you can import the module itself

#
import module
or
import package.module
or
from module import cls, func
....
shy belfry
#

__init__.py IMO is so much cleaner than the module.exports in Js.

#

But I personally also just hate ES5 modules.

ruby prairie
zenith topaz
#

Isn't it just export now instead of module.exports?

ruby prairie
#

commonjs and es6 stuff

#

require() vs import <> form ""

brazen jacinth
#

well if you have to import everything, and use it in the same namespace, that's the way to do it

#

you can import schemas, and then just call it like schemas.json() or w/e

ruby prairie
#

i need to use them in several different files and i'm just looking for the most efficient way of importing them all

#

well, efficient and cleanest

shy belfry
#

Wow, that sounds cool! Good luck with it!
@open trout thanks! I'll be using it in aPRAW soon to get an idea for how it works in a production library. (:

open trout
#

ayy :^)

shy belfry
#

like that can be moved out side of that function and replaces with a __new__ method no?
@radiant fulcrum could you explain further please? O.o

#

I got a rough idea of __new__() but apparently not good enough to understand how it would be useful here.

shy belfry
#

So I'm trying to get new to work now... Is this correct?

class AllReactive:
    def __new__(cls, org_cls):
        return type(cls.__name__, (ReactiveOwner, org_cls), {"__doc__": org_cls.__doc__})```
woeful brook
#

can any one help me [ return " ".join(final) ] ---> what is this ---> " ". what does this mean ?

shy belfry
#

If you have a list of strings, they will be joined by whatever is specified before calling join() since join() is a function on the str type. Like so for example:

l = ["str1", "str2", "str3"]
print(" ".join(l))
#

#bot-commands

woeful brook
#

@shy belfry Very Good. Thank you. Got it Now.

safe linden
#

is it common for them to add new reserved words to python? just found out about async via it breaking things

flat gazelle
#

it is quite rare, but does happen sometimes

safe linden
#

I don't really understand the new words, was curious why they added them

wide shuttle
#

async/await were added in Python 3.5 to have better support for asynchronous programming/coroutines

#

They became reserved/keywords in 3.7, I think

peak spoke
#

The only additions between 2 and 3 seem to be the singletons and then async/await ( + removal of exec)

#

so really not many changes there

#

oh and print was removed

safe linden
#

removed as a reserved word?

peak spoke
#

yes

#

Because it was a statement before,

Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print = 5
  File "<stdin>", line 1
    print = 5
          ^
SyntaxError: invalid syntax
safe linden
#

that seems an interesting choice honestly

#

well, I have a lot to go learn now, hadn't heard of singletons before and async seems kind of cool

karmic slate
#

Will converting python files to .exe increase performance or have any benefits over just python files?

open trout
#

If anything it makes them slower (the times I have frozen scripts, at least)

#

The numero uno benefit is just portability

karmic slate
#

Ok thanks 😊

tulip gorge
#

I want to test my test files pls could someone help me out

north root
#

@karmic slate unless you use something like nuitka (transpiles Python to C and compiles the C), it will be slower

karmic slate
#

Okay thank you

unkempt rock
#

hey since i from a java background, is there sth in python that is equivelent to private, public and protected?

radiant fulcrum
#

not really

#

other than naming conventions

#

_ prefixing the var name normally means it is a private varible

#

all caps normally means its a constant

wide shuttle
#

Not in the same way. The philosophy in Python is that "we're all consenting developers", although there are some conventions to indicate that some attributes are part of the internal implementation and you should mess with them at your own risk.

#

That's the single leading underscore (_) as mentioned above

#

There's also the double leading underscore variant (__attribute), which adds another layer of "you should really think twice about touching this" by slightly mangling the name of the attribute in the external view of an object. (The name of the class gets prepended.)

#

It's not meant as absolute protection/security, though; more as a safety cap on a button that you need to take off before you can press it: Are you sure you want to touch this?

unkempt rock
#

intresting

radiant fulcrum
#

you can sort of make constants by using frozen sets

peak spoke
#

The main purpose of the mangling is to prevent taking up names from subclasses, since we can use the _ prefix to mark it as "private"

radiant fulcrum
#

but normally everything is based of the general nameing convention of pep8

wide shuttle
#

The main purpose of the mangling is to prevent taking up names from subclasses, since we can use the _ prefix to mark it as "private"
@peak spoke

Yeah, that's true

unkempt rock
#

and im assuming namespaces also prevents what ur saying as taking up names right

wide shuttle
#

and im assuming namespaces also prevents what ur saying as taking up names right
@unkempt rock

Kinda, but this is more for (multiple) inheritance, where you extend the functionality of one class with others

boreal umbra
#

@unkempt rock You might also be interested in the @property decorator in Python. The default assumption in Python is that you don't need to wrap any layers around instance variables, but if you have a circumstance where you feel it's needed, @property lets you do it while ensuring that accessing (and changing) those attributes has the same syntax as regular access.

#

The dataclasses module that comes with >=3.7 also lets you make frozen instances where the process of changing attributes of an instance is really convoluted.

unkempt rock
#

@wide shuttle tx im still trying to break some of my 'java' habits

cloud crypt
#

hey, little question regarding dicts; from which version is dict order guaranteed?

peak spoke
#

Is there anything to read up on for how string interning works on cpython (or in general)?
I've got roughly 75k dict items which share a few short strings as their attributes, the values of the first string attribute also exist as dict keys and seem to be interned, but then the second attribute which contains strings is an unique object for every item

pliant tusk
#

@cloud crypt 3.6

flat gazelle
#

3.6 as an impl detail, 3.7 language spec AFAIK

pliant tusk
#

Oh it was spec in 3.7?

cloud crypt
#

3.6 I see

#

yikes time to use OrderedDict then

flat gazelle