#internals-and-peps

1 messages Β· Page 74 of 1

radiant fulcrum
#

yikes

full jay
#

@tender ingot Can you get a user id?

#

Makes it easier

tender ingot
#

724865789341204480

full jay
#

Also I'm going to move this conversation to #ot1-perplexing-regexing as this really isn't the place to discuss this kind of stuff

undone hare
#

@full jay FWIW CPython does compare the timestamp in the pyc file against the file modified timestamp given by the OS

full jay
#

Oh by the OS. Well then I'm confused as to what those two bytes represent then

#

If it just goes by the OS' timestamp

undone hare
#

They compare them

#

If the source file (OS provided) timestamp is after the pyc file (written in the file) timestamp, then you have to recompile the code

raven ridge
#

The OS is asked for the timestamp of a .py file. If there is no .pyc file or if the timestamp stored in the .pyc file is older than the timestamp the OS returned for the .py file, then a new .pyc file is written, and the .py file's timestamp is stored in it

full jay
#

Ahhh, okay so it is stored internally by the .pyc

#

Okay, that's what I wasn't sure about

spark magnet
#

these days, .pyc files can also be based on hashes instead of timestamps

unkempt rock
#

Whats the best Programming Language should I use to make a bitcoin wallet and other types of wallets?

quartz abyss
#

guys why making my script executable mess up the working of it?

raven ridge
#

these days, .pyc files can also be based on hashes instead of timestamps
@spark magnet TIL

#

guys why making my script executable mess up the working of it?
@quartz abyss wild guess: you've given the script the same name as a module that you import from the script. Because the directory that you run the script from is implicitly added to the module search path, the import finds your script instead of the module you meant to import

quartz abyss
#

nono was my fault, is just slow to start, really slow haha

#

ty anyway

raven ridge
#

I misread the question entirely, heh. I thought it was "why does changing the name of the script change the behavior". Oops πŸ˜„

strange aspen
#

hehe

fallen slateBOT
#

:incoming_envelope: :ok_hand: applied mute to @strange aspen until 2020-09-23 22:26 (9 minutes and 59 seconds) (reason: role_mentions rule: sent 4 role mentions in 10s).

north root
#

nice one

#

!ban 758437652021379122 spamming admin pings with inappropriate things

fallen slateBOT
#

:incoming_envelope: :ok_hand: applied ban to @strange aspen permanently.

meager hound
#

does anyone has any tips about where should i start to learn about factory automation with python? (not sure if this is the propper channel for this question but i'll give it a try)

#

i founded some videos about a guy named Jonas Neubert (very good by the way) but I was looking for something more like a book

magic python
#

If one does dir( ) on an object then it shows the attributes of that object, is something like str an attribute of something though?

#

when I do dir( ) without an object it returns the variables which are in memory πŸ€”

pearl river
#
dir(__builtin__)

is probably what you need.

magic python
#

undefined for me actually πŸ€”

#

ooooo , ok - this is something i was wondering about the other day I think, or related to - why isn't __builtin__ defined in pdb session?

#

my previous question wasn't exactly that, but that's what I"ve just bumped into when trying to run the above, and I don't really understand what's going on there, or how I'd go about finding out

pearl river
#

it might actually be an ipython thing, no idea if it's normally defined. πŸ˜…
Maybe __builtins__? And also I think you can import them.

magic python
#

no - __builtin__ works alright in a typical session, but not in a pdb... oh i see what you mean, i'll check

#

yeah - seems to be an ipython thing

#

__builtins__ does work though, this seems odd to me

pearl river
#

so I guess ipython reexports __builtins__ under the name __builtin__ in addition to the normal one

#

I'm sure there was a reason for that at the time πŸ˜›

magic python
#

i don't think i like that, but I am not qualified to complain properly lol

meager hound
#

@lucid oyster I founded the second edition of this book on my yesterday research but I was looking for something a little more specifig like modbus protocole and plc integration! This is a little generic.. like for automation of daily routines... But thanks man for your help

lucid oyster
#

Hmm

meager hound
#

seems a nice field for python developers πŸ™‚

lucid oyster
#

Interesting

#

My internet is setup in a way that it blocks the connection but try these two on pdfdrive, i cant open them atm

meager hound
#

wow this seems exactly what i'm looking for !! nice brow

#

just not sure if it is python related

lucid oyster
#

I am not sure about that sadly

#

Its a very niche field

#

He does PLC programming which is usually done by python

#

So its definitely related

meager hound
#

i didn't opened it yeat, was just judging by the cover but i'm on my way to find out

lucid oyster
#

Guys on r/Automate say that python is not really great for industrial automation

#

Soo yeah, Its not that advanced

#

Keep looking tho, there might be smthin

meager hound
#

there's a lot related to raspberry and is kind of easy to use python on it. I think i'll start digging on it.. I really appreciate your effort on the researches 🀘

swift imp
#

Is there a pattern for creating an api to commonize to different object interfaces?

paper echo
#

@swift imp can you give an example?

swift imp
#

There's bokeh figure objects and matplotlib figure objects

#

Want to create a single interface that abstract some common functionalities

#

I guess I can just use single dispatching

paper echo
#

makes sense, unless you want to create a wrapper class, but it will still be single dispatch internally

swift imp
#

Yeah

#

I like that idea

meager hound
#

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

hexed skiff
#

hello every1

#

can anyone explain me what this code is:

#

def f(a, l[]):
l.append(a)
return l

f(1)
f(2)
print(f(3))

unkempt rock
#

ok?

feral cedar
#

that doesn't look valid

raven ridge
#

Looks like it's missing an =

covert saddle
#

yeah or some weird c++ python lovechild

unkempt rock
#

looks like a mixture of c++ and python

#

It looks like an error

raven ridge
#

it looks absolutely nothing like C++ πŸ˜„

#

it's literally Python with 1 missing character.

flat gazelle
#

!e

def f(a, l=[]):
    l.append(a)
    return l

f(1)
f(2)
print(f(3))
fallen slateBOT
#

@flat gazelle :white_check_mark: Your eval job has completed with return code 0.

[1, 2, 3]
flat gazelle
#

it probably demonstrates this once you correct it

raven ridge
#

The same thing in C++ would be:

#include <iostream>
#include <vector>

std::vector<int> default_l;
std::vector<int> f(int a, std::vector<int> & l = default_l)
{
    l.push_back(a);
    return l;
}

int main()
{
    f(1);
    f(2);
    for (auto x : f(3)) {
        std::cout << x << std::endl;
    }
}
#

so - not very similar.

flat gazelle
#

does it have the same behaviour?

raven ridge
#

yep, output is:

1
2
3
flat gazelle
#

but it would be 3 if nt> & l had the & removed, right?

raven ridge
#

yes.

unkempt rock
#

yeah the same thing

#

anybody wanna work with me on a python app tkinter

safe hedge
#

Does anyone know of a common library which uses the newer implicit namespace packaging style?

prisma eagle
#

it's not really a "newer style"; it's just a new feature for the cases for you do want a namespace package. you just.. almost never actually want a namespace package

proper vessel
#

i m looking for some projects as a beginner send helpPES3_Cry

raven ridge
#

@safe hedge why do you ask?

safe hedge
#

I wanted to run some pkgutil stuff on one to see if it behaves like a normal package

#

Just interested really since I've been using pkgutil a lot trying to get this plugin thing working

prisma eagle
#

it doesn't; namespace packages are an utter pain in general and don't really behave like normal packages

safe hedge
#

I could mock my own but I was being lazy

raven ridge
#

It's trivial to make your own... Easier than installing one, frankly. Create an empty directory, create a Python file in it. Done.

safe hedge
#

Mainly I want to know what happens if you import a namespace package and do __path__

raven ridge
#

What I just said is sufficient to test that. Though the PEP explains it in detail.

#

Basically, it behaves just like it used to with explicit namespace packages, but slightly better.

austere jewel
#
Hello from the pygame community. https://www.pygame.org/contribute.html
2020-09-24 12:08:16.346 Python[38515:2002322] ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to (null)
Unable to obtain graphics context for NSWindow (Mojave behavior)```
#

CAN SOMENE PLZ HELP

safe hedge
#

It's been a long day I didn't even think to read the PEP

raven ridge
#

!pep 420

fallen slateBOT
#
**PEP 420 - Implicit Namespace Packages**
Status

Final

Python-Version

3.3

Created

19-Apr-2012

Type

Standards Track

safe hedge
#

Yeah I just took a look. Seems like __path__ would still be usable same as a non-namespace pkg

raven ridge
#

Except that it can contain more than one entry, yeah

cedar harness
#

Hi

#

Do you guys think we can write a code to calculate space complexity of a python program

#

Like rather than looking at the code and figuring out the complexity

#

A program that looks at the code and calculate complexity

flat gazelle
#

I am pretty sure you will run into the halting problem

#

It may be possible with something like agda's enforced total functions

somber halo
#

You might get somewhat there by using something that figures out the McCabe complexity. Flake8 provides that out of the box.

safe hedge
#

Except that it can contain more than one entry, yeah
@raven ridge __path__ returns an iterable anyway though, and for what I have been doing you can just pass __path__ into pkgutil.iter_modules since it takes an iterable

teal yacht
#

I am pretty sure you will run into the halting problem
@flat gazelle This, finding complexity of arbitrary programs, whether it is space or time is undecidable

#

cyclomatic complexity is also very unrelated to computational complexity, it's (or its usefulness rather) actually closer to psychology than to computer science

cedar harness
#

Oh okay got it

#

So before runtime it's basically impossible to calculate

magic nova
#

for arbitrary programs, yes

rugged shadow
#

rock_dir = os.path.join('/tmp/rps/rock')

paper_dir = os.path.join('/tmp/rps/paper')

scissors_dir = os.path.join('/tmp/rps/scissors')

What is the use of os.path.join in these situations?

I think this would be just as fine:-

rock_dir = '/tmp/rps/rock'

sacred yew
#

it does nothing in your code @rugged shadow

sick adder
#
    def createFolder(directory):
        try:
            if not os.path.exists(directory):
                os.makedirs(directory)
        except OSError:
            print ('Error: Creating directory. ' +  directory)
            

    # Example
    createFolder('.\\'+ str(guild.id) +'\\')
``` I'm runin this, but it isn't working
undone hare
grave jolt
#
def foo.bar(hello):
    print("world")

def foo["bar"].baz(hello):
    print("world")

instead of

def _foo_bar(hello):
    print("world")
foo.bar = _foo_bar

def _foo_bar_baz(hello):
    print("world")
foo["bar"].baz = _foo_bar_baz

Tolerable or outrageous?

grand crag
#
def System.out.println():
``` ^ outrageous πŸ˜‚
sacred tinsel
#

I want to be outraged but am not

grave jolt
#

well, you can already do this πŸ˜›

@myobj.setattr(foo, "bar")
def _foo_bar(hello):
    print("world")
#

and maybe you could do a decorator like this

@F.foo["bar"].baz
def _(hello):
    print("world")

that would do stuff with frames

modest pumice
#

I have created a registration page, and I need a unique id in it
This is the requirement -
Unique Id :- it would be a six digit alpha numeric combination unique if it isn’t entered by the
user it would be auto generated from backend.

#

And I have created this registration page using django.. Can anyone help, please?

sacred yew
#

wrong channel @modest pumice

modest pumice
#

Sorry!

boreal umbra
#
def foo.bar(hello):
    print("world")

def foo["bar"].baz(hello):
    print("world")

instead of

def _foo_bar(hello):
    print("world")
foo.bar = _foo_bar

def _foo_bar_baz(hello):
    print("world")
foo["bar"].baz = _foo_bar_baz

Tolerable or outrageous?
@grave jolt I can't get behind this because it means the names of functions now have to be evaluated as expressions

near whale
#

can someone help me create a discord bot??

lavish aspen
#
def foo.bar(hello):
    print("world")

def foo["bar"].baz(hello):
    print("world")

instead of

def _foo_bar(hello):
    print("world")
foo.bar = _foo_bar

def _foo_bar_baz(hello):
    print("world")
foo["bar"].baz = _foo_bar_baz

Tolerable or outrageous?
@grave jolt

@partial(foo.__setattr__, "bar")
def _(who):
    print("hello ", who)
grave jolt
#

uh... no, thanks

#

@boreal umbra What do you mean? The names will be something like 'foo.bar' and 'foo["bar"].baz'

boreal umbra
#

@grave jolt if the line def foo.bar(...): has the effect of making bar an attribute of foo

#

then the name of the function is being evaluated

hollow crane
#

yeah what about def foo.findChild("bar")[0].baz()

boreal umbra
#

currently naming a function is basically the same as naming a variable, I believe.

grave jolt
#

@boreal umbra I don't understand what you mean and why that's a problem.
A function can have any name whatsoever, and it's assigned at the time of creating the function

#

!e

import dis

def f():
    def g():
        pass
    return g

dis.dis(f)
fallen slateBOT
#

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

001 |   4           0 LOAD_CONST               1 (<code object g at 0x7ff549a2dc90, file "<string>", line 4>)
002 |               2 LOAD_CONST               2 ('f.<locals>.g')
003 |               4 MAKE_FUNCTION            0
004 |               6 STORE_FAST               0 (g)
005 | 
006 |   6           8 LOAD_FAST                0 (g)
007 |              10 RETURN_VALUE
008 | 
009 | Disassembly of <code object g at 0x7ff549a2dc90, file "<string>", line 4>:
010 |   5           0 LOAD_CONST               0 (None)
011 |               2 RETURN_VALUE
grave jolt
#

So the name can be computed at runtime, but, well, it could be just static like 'foo.bar'

boreal umbra
#

but if naming the function foo.bar does something other than just naming the function, now that can cause errors

#

right?

#

wouldn't you get a name error if foo isn't in that namespace?

unkempt rock
#

can someone help me create a discord bot

grave jolt
unkempt rock
#

what do you guys do here

grave jolt
#

@boreal umbra

def foo.bar(hello):
    print("world")

will be roughly the same as

def _foo_bar(hello):
    print("world")
_foo_bar.__name__ = "foo.bar"
# or, alternatively:
_boo_bar.__name__ = repr(foo) + ".bar"
# (doesn't really matter)
foo.bar = _foo_bar

well... yeah, you will get an error if foo is not found, why is that a problem?

boreal umbra
#

@unkempt rock this channel is about in-depth discussions about Python itself

#

@grave jolt it's not a problem if you're okay with that being possible, but the only type of error you can get when you name something is if you use an illegal character in the name (or start with a numeric character, I guess)

#

and I would want naming functions and classes to be the same way.

grave jolt
#

I mean, if foo is not found you will get an error either way πŸ€·β€β™‚οΈ

boreal umbra
#

but giving the function to foo after the fact is a different kind of expression than just naming the function

grave jolt
#

Well, my proposal is just syntax sugar for defining a function and assigning it as an attribute

boreal umbra
#

I see where you're coming from

grave jolt
#

I don't think it really needs to be added to Python (that's kind of a rare scenario), just a thought

boreal umbra
#

fair enough

#

I wouldn't want to encourage people to retroactively add methods to classes

#

even though I think it's cool that you technically can

grave jolt
#

I don't think it really needs to be added to Python (that's kind of a rare scenario), just a thought
It's usually done as a decorator like this when it's needed:

@app.post("/users")
boreal umbra
#

to me that makes it clear that the function being defined is being used in someone's API, or something along those lines

#

but I guess there's no reason why that's better for that than the syntax you've proposed.

half wolf
#

Adding methods to classes van be great, if the language is made for it. Python is not :(

#

@grave jolt multi line lambda would be better probably.

flat gazelle
#

I mean, type(thing).method = function is fine, though with some footnotes

grave jolt
#

*<Something>.prototype.<method> = ... flashbacks*

half wolf
#

It's not fine at all. The problem is that import order is such a mess. There's no reasonable way to set up all such modifications before your main program starts imo.

#

In objective c and swift this works great and is well defined.

radiant fulcrum
#

JS would say otherwise :P

grave jolt
#

Well, my idea was more about assigning functions as attributes to objects, like

async def bot.on_message(ctx, message):
    ...
radiant fulcrum
#

I do that

#

well not litterally that

#

but with the d bot example

flat gazelle
#

there are definitely cases where you do not want both the function name and the decorator name

grave jolt
#

well, yes, when the name gets expected, for example

radiant fulcrum
#

methods change between development mode and prod mode for us so things like on_ready events have to be dynamically done

grave jolt
#

and decorators have more flexibility, like keyword arguments (however, I think there's a proposal, to allow kwargs in indexing?)

radiant fulcrum
#

i feel like it could be useful but would probably create way more confusing things than it solves

#

the option would be nice though

#

especially useful for something like pandas

grave jolt
#
# cool
@app.post("/users", response_model=User)
def register_user(
    username: str = Body(...),
    email: str = Body(...),
    password: str = Body(...)
):
    ...

# this could work, but the name isn't inspectable
# (FastAPI actually does inspect it, and it puts it in `openapi.json`)
def app["post", response_model=User](
    username: str = Body(...),
    email: str = Body(...),
    password: str = Body(...)
):
    ...

#  well... maybe... but... meh
def app["post"]["response_model", User](
    username: str = Body(...),
    email: str = Body(...),
    password: str = Body(...)
):
    ...
radiant fulcrum
#

oh yikes no

minor locust
#

is defaultdict(int) basically Counter()?

#

pros/cons using one over the other?

minor locust
#

thanks

noble kelp
#

yo this a decent place to ask a kinda snaggletoothed nginx/flask/swagger thing?

#

nvm, just saw the "it's not a help channel" bit, my b

next falcon
#

I asked a question in the help channels and I was instructed to ask here, in case there is a more obscure way to deal with the issue than the obvious ones.

#

I have created a function which takes a dictionary as an input. Inside the function the dictionary is gradually becoming empty and as I became painfully aware, when this happens the dictionary will remain empty forever since its mutable.

The problem is that I need to call the function more than 1 times with the same dictionary. I know i can create copies of the dictionary but I might have to do thousands of function calls using this dictionary.

#

I did finally, everytime I called the function, create a copy of the dictionary inside the function and work with the copy, so that the original remains unchanged. This pretty much solved the issue but Im talking about thousands of function calls here, so this copy() command might take some time overall

#

I was wondering, therefore, if there is a more advanced way to do something here. Thanks in advance. If anyone wants me to post the code or anything let me know. I dont post it beforehand in order not to cluster the chat

fallen stream
#

can someone help me with my python

pliant tusk
#

@next falcon just use .copy() its implemented in C and def wont cause any huge issues with your code unless your talking a dictionary with 100k+ items

#

trust me the python is taking longer

next falcon
#

Well, largest dictionary will have 60k keys, and each value is another dictionary, albeit with less keys hehe

#

Perhaps you're familiar with the topic, I just want to pretend its an adjacency list. I try to implement dijkstras algorithm but for an immense graph.

pliant tusk
#

id still say just use .copy()

next falcon
#

Ok, I will just pass the dictionary in the function then but work with its copy every time. Thanks chilaxan

deft pagoda
#

or don't mutate the dict and you don't have to copy it

pliant tusk
#

^ thats also an option

unborn raven
#

hey guys i have 50/50 odds of winnin/losing, how do i calculate odds of winning/losing multiple times in a row

radiant fulcrum
#

thats not what this channel is about really

unborn raven
#

ok

radiant fulcrum
#

and thats just basic probability

unborn raven
#

can u help?

radiant fulcrum
#

im about to sleep

unborn raven
#

ok

feral cedar
unborn raven
#

i did open some channel

next falcon
#

@deft pagoda I am sorry for the ping, I just saw your message. Can you explain what yo mean "dont mutate"? I have to work on it so its going to be changed, am I wrong?

deft pagoda
#

you shouldn't need to modify the dict for djikstra's

next falcon
#

Oh ok. The way Im doing it is to, in every round you find the minimum path to a node, so you remove the node from the graph

#

There are better implementations i guess. This one is too slow as well sadly

#

For a graph of 60k nodes, it took me 5 minutes :/

deft pagoda
#

you should instead keep a set of seen nodes

#

and not mutate your graph

next falcon
#

oh, now i have a set of unseen nodes

deft pagoda
#

that works too

#

also for large graphs, dijkstra's will take a while in python

next falcon
#

Ah, its expected? Thats good to know.

#

I'll try your suggestion, modify the code to use a set of seen nodes so I dont have to mutate the initial graph.

deft pagoda
#

i mean, you can time networkx's algorithm vs yours

next falcon
#

Although the copy() command probably doesnt take 1 second even.

deft pagoda
#

will probably be on the same order of time

next falcon
#

I wasnt aware of this module. Might try it. Thanks

next falcon
#

Thank you πŸ™‚

fierce zephyr
#

how do public apps hide api keys while letting the app users use the app?

#

I am using the imgur api to upload images
Is it ok to give all the clients the client ID and client secret?

grave jolt
#

@fierce zephyr What do you mean by "hide API keys"?

#

What do you mean by 'clients'?

fierce zephyr
#

Those who use the app

#

By "api keys" I mean the client secret and client ID

grave jolt
#

"client ID" and "client secret" are just authentication information for you your account.

#

Like username and password.

fierce zephyr
#

So it's fine to give them to everyone?

grave jolt
#

Well, each user of an API has their own API credentials, just like they have their own password and username (how else would you authenticate yourself?)

#

Anyway, this isn't really on topic for this channel

fierce zephyr
#

They don't have their own client ID and client secret

#

You obtain them by registering your app

grave jolt
#

Your app is the user of the imgur API.

#

Just like @fallen slate is the user of Discord API.

fierce zephyr
#

By user I mean

#

Those who download/use my app

grave jolt
#

Anyway, this isn't really on topic for this channel

fierce zephyr
#

Is it okay to give it away to them?

safe hedge
#

Although the copy() command probably doesnt take 1 second even.
@next falcon Since your dict is a dict of dicts be careful you don't need to use deepcopy instead. copy will just create a shallow copy and I think those nested dicts will just be references to the originals. That may or may not be a problem and you'll need to test that I suspect

round kelp
#

yeah shallow copy just references the original one but deepcopy will copy the data into the new variable without any references

raven ridge
#

well, into a new variable without any references to the original one.
After import copy a = {"x": [1]} b = copy.copy(a) the items a["x"] and b["x"] are references to the same list.
After import copy a = {"x": [1]} b = copy.deepcopy(a) the items a["x"] and b["x"] are references to different lists with the same contents.

wispy plover
#

Hi all, I’m not having much luck on the general channel. I’m hoping to get some help with my code, https://mystb.in/IngCitizenshipRemainder.python how can I call the function find_all_entries within the β€˜for thing’ loop? That’s where I must be going wrong? I want to process each posts response for the json then post the next entry. How can I do this? Can someone help me please? Thank you

paper echo
wispy plover
#

@paper echo ahh thank you so much

brave badger
#

Thoughts on:

(int, int)  # Tuple[int, int]
(int, ...)  # Tuple[int, ...]
[int]       # List[int]
```?
red solar
#

in what respect?

charred wagon
#

As a replacement for current type annotation syntax

#

I don't really like it. It breaks consistency with other type annotations. There isn't room to come up with such syntax for all types.

#

I imagine it will visually be easily confused for actual tuples/lists

#

At least at a glance

teal yacht
#

I think unions and product types should have first class syntax support for sure, not sure about that list one tho, never been a fan

#

we discussed int | bool | T before as well

#

for Union[int, bool, T]

#

we could even stay consistent, as in use binary operators that we can overload, and use ML syntax and use * for tuples

#

giving int * bool * T == Tuple[int, bool, T]

raven ridge
#

I think I'd prefer (int | None) over Optional[int] now that you mention it...

sacred yew
#

union syntax seems nice

raven ridge
#

Or even or for that matter

sacred yew
#

Not sure about the *

teal yacht
#

* wouldn't actually be consistent because tuples are arrays in python, not actual product types

red solar
#

that feels more like a technicality than something that would matter

teal yacht
#

no because the fact that the 1-uple exists breaks stuff

red solar
#

ah :/

#

i wanna say this makes me uneasy, but idk why, or how to express it (pure's suggestion)

jovial stream
#

what does this mean?

#
enumerate(zip(*lst))
#

I think I know what enumerate is. ['s', 'a', 'b'] would be 0, s/ 1, a/ 2, b

brave badger
#

zip(*lst) transposes the given list

jovial stream
#

i feel stupid idk what that means

#

zip( [1,2], [a,b] ) = [ (1,a), (2,b) ]

#

is that right?

teal yacht
#

yes

brave badger
#

It "flips" a list diagonally e.g.

x = [ (1, 2)
    , (3, 4)
    , (5, 6)
    ]
# becomes
y = [ (1, 3, 5)
    , (2, 4, 6)
    ]
```Terrible formatting, but yes
jovial stream
#

oh

#

reminds me of matrix transposition in lin-alg

#

i didn't think u meant that when u said transpose

teal yacht
#

yes that's exactly the same transpose

brave badger
#

Pretty useful pattern when undoing a xys = zip(xs, ys)

jovial stream
#

how do I know what *lst does?

#

terminal keeps giving me errors

teal yacht
#
xs = [1, 2, 3]
foo(*xs)
# same as
foo(1, 2, 3)```
#

it's called unpacking or a starred expression

jovial stream
#

so it turns it from a list to

#

that

#

idk what to call that

#

['hello', 'hey', 'ok'] = 'hello', 'hey', 'ok'

teal yacht
#

it unpacks it, there's no syntactical structure that holds it

jovial stream
#

yea so

teal yacht
#

hence why you were getting errors

jovial stream
#

you could use that as 3 parameters

teal yacht
#

it's only valid in certain contexts

#

yep

jovial stream
#

is that right?

#

but the zip we did took 2 paramters

teal yacht
#

zip takes N parameters

jovial stream
#

yes but like

#

those were lists in itself

#

but this is just parameters of a bunch of strings then

teal yacht
#

you can zip strings too

jovial stream
#

how would you transpose 3 strings

#

oh ok

#

wait l

#

let me work this out on paper

teal yacht
#

you are transposing the list of strings, not the strings themselves, you are zipping the strings

jovial stream
#

would like

#

'hello' = ['h', 'e', 'l', 'l', 'o'] basically be the same in this context?

#

because both can take [0] as a argument

#

indice the same

teal yacht
#

yes, in this context both are the same

#

try it with a small example input really, it'll be more obvious

jovial stream
#

do they have to be the same length?

#

i would think so

teal yacht
#

yes, or the longer ones will truncated up to the length of the smallest one

jovial stream
#

oh python truncates it

#

that's nice!

teal yacht
#

it's an implementation detail of zip

#

there's zip_longest in itertools, which doesn't truncate

jovial stream
#

zip(β€˜flower’, β€˜flow’)

{
f l o w e r
f l o w
}

=

ff ll oo ww

#

is this correct?

teal yacht
#

yes

mint forge
#

can i ask about decorators here?

amber nexus
#

Probably not a suitable channel for that no

#

Maybe a help channel

jovial stream
#

@teal yacht thank you i understand it now

#

appreciate it ducky_santa

ionic fulcrum
#

ive been unable to pass out my Python exam. Can someone help me out to easily remmember the lang??

red solar
#

probably, but not in this channel

gleaming rover
#

is there any technical reason => lambdas can't be made available in Python?

#

like parser limitations

flat gazelle
#

well, with the new parser, probably not

#

with old one, maybe

undone hare
#

It should have been possible with the old parser

flat gazelle
#

ye, the lexer can deal with the ambiguity there

undone hare
#

Even the parser itself should have been able to parse that correctly

#

Well, you are correct (not sure why you deleted), but by a simple lookahead it should have been able to know if it is a tuple or a lambda

#

That's the "dangling else" problem described in the dragon book

flat gazelle
#

because it could, which is why

(a, b)
(a, b) = b, a
``` are both possible despite `(a, b)` meaning different things in either case
undone hare
#

Yup

flat gazelle
#

so I guess it is possible

gleaming rover
#

how would you feel

#

about => lambdas

peak spoke
#

Meh, never had a huge need and python's design doesn't make the statements inside very nice

undone hare
#

I dunno, although the current lambda syntax is very meh IMO

safe hedge
#

What's the problem with it?

undone hare
#

I don’t know, it doesn’t really feel as natural as the rest of the language does

flat gazelle
#

It is very scheme like, and that is not a great thing in a language that is not scheme.

gleaming rover
#

I dunno, although the current lambda syntax is very meh IMO
@undone hare it is

#

and it's mildly irritating having "lambda" be a keyword

#

IMO the "lambda niceness hierarchy" goes like (a, b) => a + b > \a b -> a + b > lambda a, b: a + b > [](auto a, auto b){return a + b}

#

but I feel like neither of the first two would really fit in Python

peak spoke
#

The expression restriction is pretty big but I think it fits in with python's design

mint forge
#

where do we use decorators?

red solar
#

@undone hare u read the dragon book? (The compiler one)

flat gazelle
#

often, it is to transform the function into an object (@property @contextmanager)or to add it to some internal list (@typing.overload, flask route decorators)

mint forge
#

huh

#

idk what those are lakamatiol i just started decorators

#

do u have a simpler answer?

#

ig no

peak pollen
#

To make the same change to multiple functions without duplicating code?

mint forge
#

well, sorry the description is not so clear i will just grab a help channel

wide shuttle
#

@mint forge This channel is not for asking help question or help with learning how Python works. Instead, this is a discussion channel meant for people who are already comfortable with the language to discuss the language itself. That's why it's in the "Discusssion" category as well. The idea is that we have a lot of channels where asking for help is totally on topic and we want to have at least one channel where Python itself can be discussed, where people can have a conversation about that goes deeper into the language, and talk about the advanced concepts that are part of the language.

#

I think we already provide a lot of space in our community where you can ask for help with understanding and learning Python; this channel is specifically not meant for that.

mint forge
#

ok

undone hare
#

@undone hare u read the dragon book? (The compiler one)
@red solar yes, u am reading it lemon_pleased

lofty rover
#

So I'm going to do some automation with headless selenium and am going to make a seperate environment for this

#

I currently run ubuntu on WSL with venv and anaconda just on my win10 base

#

Do you guys recommend setting up an environment in wsl? Is this easy to combine with stuff like vscode?

#

Alternatively, I can of course just create a conda env just in win10, but I heard setting up environments in wsl can be very helpful

mint forge
#

for help get a help channel

grave jolt
#

@uneven oyster This is not a help channel, it's a discussion channel (see channel description). To get help, see #β“ο½œhow-to-get-help.

uneven oyster
#

Oh sorry, in the help channel the question is usually gone in a few secs :C

wide shuttle
#

@uneven oyster You should be able to claim your own help channel for your question, see the channel linked above. You will get an entire channel specifically for your question.

uneven oyster
#

Oh wow I didn't know, thank you. I will have a look but right now fix error seems to help me in another channel already where's not many people πŸ™‚

#

There seems to be no available channels

#

Or I'm not looking good

undone hare
uneven oyster
#

Ah thanks!

undone hare
#

np

gusty marsh
#
solution=lambda n:all(k%i for i in range(2,int(k**.5)+1))if(k:=n**.5)==k//1<n else 0``` how can i make this code faster it returns True if the number has 3 factors and false if it has less than 3 factors
#

like the fastest code possible for this

#

i tried this

uneven oyster
#

Let's say it even better. I have a 2D list where I want to append other arrays too.
[1] Array1, Array2
[2] Array1, Array2
......
[6] Array1, Array2

How could I do that without pre-defining the array size

#

Only define the max
[1]
[2]
.....
[6]

visual shadow
#

Append should immediately make you think of lists. Append is an insanely inefficient operation on arrays.

#

So one choice is to use a list first while appending and convert the entire thing to an array at the end.

#

Another as you mentioned is creating the entire array in one go and filling it up later.

#
solution=lambda n:all(k%i for i in range(2,int(k**.5)+1))if(k:=n**.5)==k//1<n else 0``` how can i make this code faster it returns True if the number has 3 factors and false if it has less than 3 factors

@gusty marsh probably not the right room for this, though I'm not sure where your question belongs.

feral cedar
undone geyser
#

hello has anyone installed pybullet for windows 10 here?

charred wagon
#

I'm busy now anyway so someone else will have to help

modern frigate
#

How are computers able to understand the length of a second? time.sleep is able to pause the program for around 1.00 every time, give or take.

peak spoke
#

There's a physical "clock" in your computer to keep track of time, then when you do time.sleep python tells the os you want the thread to sleep for that amount of time and then it's managed by the os' scheduler

half wolf
#

The time is periodically synced with NTP to a time server too, which means it's in sync with an atomic clock somewhere.

swift imp
#

I think this is an extremely bad example

#

Pandas would never do that

#

And what if you wanted to combine it with another logical mask

#

Nit picky but yeah, they should change that

teal yacht
#

yeah this feels like the one who wrote this example doesn't understand what it does

#
obj[spam=1, eggs=2]
# calls type(obj).__getitem__(obj, (), spam=1, eggs=2)```uhhhhhhh, why is that passing an empty tuple, i don't get why the semantics should be different from function calls
flat gazelle
#

Because you need a positional arg there for backwards compat

teal yacht
#

can you provide an example where it breaks ? i don't see how that causes any issue given it's up to the type maintainer to allow for keyword arguments in {get,set,del}item

flat gazelle
#

Actually, nvm.

deft pagoda
#

here's a fun exercise:

In [91]: x = 3
    ...: x = maybe(None)
    ...: print(x)
    ...: x = maybe(100)
    ...: print(x)
3
100

None-aware function

#

it's pretty robust:

In [95]: x, y = 3, 4
    ...: x, y = maybe(None)
    ...: print(x, y)
3 4

In [96]: class Test:
    ...:     x = 100
    ...:     def reset(self):
    ...:         self.x = maybe(None)
    ...:

In [97]: t = Test(); t.reset(); print(t.x)
100
swift imp
#

Man you want these so bad lol

#

I don't blame you

deft pagoda
#

i would trade ternaries for none-aware at this point

prisma eagle
#

i want real sum types so bad

grave jolt
#

@prisma eagle https://gist.github.com/decorator-factory/b2fd85ef8248c9230835461c1ec24597

In [6]: class EitherStrInt(SumType):
   ...:     Left.of(str)
   ...:     Right.of(int)
   ...:

In [7]: e = EitherStrInt.Left("Error! Lorem ipsum dolor sit amet")

In [8]: e
Out[8]: 'Error! Lorem ipsum dolor sit amet'

In [9]: type(e)
Out[9]: embellished('EitherStrInt.Left', <class 'str'>)

In [10]: [isinstance(e, EitherStrInt),
    ...:  isinstance(e, EitherStrInt.Left),
    ...:  isinstance(e, EitherStrInt.Right),
    ...:  isinstance(e, str)]
Out[10]: [True, True, False, True]
#

yeah, this is weird and needs some changes

teal yacht
#

not a fan of ADTs without a proper way to deconstruct them

grave jolt
#

yeah...

teal yacht
#

just like i'm not a fan of adding a way of deconstructing types without ADTs...

#

(go away match)

gleaming rover
#

not a fan of ADTs without a proper way to deconstruct them
@teal yacht real programmers use .get()

teal yacht
#

i bet you're the kind of people that uses unwrap in rust

grave jolt
#

Well, we already have namedtuples and dataclasses, they can serve as ADTs. And the pattern matching PEP proposes a @sealed thingy that would make it better.

#

but, well, Python isn't statically typed, so many things will be weird

full jay
#

I really need to make better use of namedtuples. I've neglected them so

teal yacht
#

oh it does ? i guess i haven't looked at it in weeks now

gleaming rover
#

i bet you're the kind of people that uses unwrap in rust
@teal yacht why flatmap when you can map and flatten πŸ™‚

grave jolt
#

ah yes >>=

gleaming rover
#

ah yes >>=
@grave jolt that's a syntax error by the way

#

you can't right shift into assignment

#

πŸ™‚

teal yacht
#

not in the correct language

sacred yew
#

haskel

gleaming rover
#

it's a joke...

#

I know it's Haskell

grave jolt
#

!e

x = 64
x >>= 4
print(x)
fallen slateBOT
#

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

4
teal yacht
#

emphasis on correct

gleaming rover
#

STOP

#

I'M SORRY

#

hm

#

in-place operators can't return things, right

#

yup, they can't

#

oh well

prisma eagle
#

@grave jolt namedtuple is a blight; it's pretty far away from real ADTs

gleaming rover
#

had brief visions of turning __irightshift__ into bind

prisma eagle
#

namedtuple is almost never the right answer

full jay
#

namedtuples have plenty of powerful uses

grave jolt
#

well, there's also NamedTuple

spark magnet
#

the thing i like best about namedtuple is that it gives us this mind-twisting definition: a tuple is a namedtuple without the names.

teal yacht
#

in-place operators can't return things, right
@gleaming rover wdym by inplace here ?

prisma eagle
#

@full jay any that isn't handled better by attrs/datacalss?

gleaming rover
#

@gleaming rover wdym by inplace here ?
@teal yacht __i dunders

full jay
#

Sometimes you don't need that extra functionality you would get from a dataclass

#

Or you only need it in a few places

deft pagoda
#

well, named tuples are probably faster with less implicit code

teal yacht
#

ah, yeah they can return stuff, and in fact they should

sacred yew
#

@prisma eagle much more efficient than dataclasses

prisma eagle
#

@sacred yew "efficient"?

sacred yew
#

less mem

grave jolt
#

@teal yacht I suppose they meant that you can't do x = (y >>= z)

gleaming rover
#
>>> class X:
...     def __iadd__(self, other):
...             return 3
... 
>>> a = X()
>>> a += 1
>>> a
3
prisma eagle
#

@sacred yew attrs with frozen=True; done

full jay
#

Ehh... less memory doesn't mean more efficient

sacred yew
#

also faster

deft pagoda
#

i modified cluegen, so I could create classes with almost no boilerplate:

from .cluegen import Datum, CachedDatum

class Expr(Datum):
    pass


class Op(Expr):
    op, func
prisma eagle
#

yes, several people have said "faster", and i don't believe it at all without an example

deft pagoda
#

ascending past dataclasses

grave jolt
#

!e

do=lambda x:x

@do
def f():
    x <- getLine
    y <- getLine
    putStrLn (show(x) ++ ", " ++ show(y))

# Valid python, can't complain
fallen slateBOT
#

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

[No output]
teal yacht
#

no stop aaa

full jay
#

Like I get what you're saying, @prisma eagle, but it's a matter of the right tool for the right job. Sometimes you don't need to or want to deal with making a dataclass. Sometimes you just need a convenient little thing. There is such a thing as class bloat

prisma eagle
teal yacht
#

i don't remember when i was writing a new piece of code and actually added a namedtuple, however, it definitely has uses as a drop-in replacement for tuples to make the code clearer

full jay
#

So I should have to get a third party library for something that I can do natively? Or is that just listing an example. I get why you might not want to use it, but it's an odd hill to die on

grave jolt
#

@full jay Well, you can use dataclasses with frozen=True

full jay
#

But again, I don't always need all the extra bits and bobs you get with the dataclass

deft pagoda
prisma eagle
#

@teal yacht sure; that is the one use case that namedtuple is actually useful: backward compatibility in cases where you returned a tuple previously

spark magnet
#

that is what namedtuples were made for

prisma eagle
#

@full jay i've used attrs longer than dataclass has existed; i don't think dataclass is very good or worth using. the points made in the docs aren't specific to attrs at all

full jay
#

It... it calls them "type clues"?

deft pagoda
#

don't argue with beazley, accept it

full jay
#

@deft pagoda What black magic is this that calls them "type clues"

deft pagoda
#

it's beazley, the antichrist of python

full jay
#

Seems like it

deft pagoda
#

he's amazing

prisma eagle
#

@full jay paradoxically, namedtuple gives you "extra bits and bobs" that aren't actually possible to turn off, like being iterable

#

attrs/dataclass lets you choose which parts you want

gleaming rover
#

^

#

If you want a tuple with names, by all means: go for a namedtuple.

#

the site put it well, I think

full jay
#

Fair enough

#

I'm more than happy to change my mind and be proven wrong

deft pagoda
#

cluegen is great because it only creates code for methods when you call the methods --- otherwise it won't bother

#

lazy code gen

full jay
#

That feels dirty

deft pagoda
#

it's sweet

full jay
#

But like... an intriguing dirty

prisma eagle
#

i used to use namedtuple like this too before i started finding it exceptionally frustrating. all i want is classes without boilerplate, and i've started using classes more now with attrs because they're so much easier to write

gleaming rover
#

i used to use namedtuple like this too before i started finding it exceptionally frustrating. all i want is classes without boilerplate, and i've started using classes more now with attrs because they're so much easier to write
@prisma eagle exact same experience

prisma eagle
#

default values for attributes is the thing i'd consider the absolute bare minimum tbh, which namedtuple doesn't offer

deft pagoda
full jay
#

Salt, you are the master of the esoteric and the amazing

gleaming rover
#

that is actually so cool

teal yacht
#

ngl, i don't see the difference with attrs/dataclasses in that example

full jay
#

wha... what are the characters in lines 39 and 41

prisma eagle
#

@teal yacht what example

gleaming rover
#

the same ones used in tree, I'd guess

teal yacht
#

the one salt-die posted

full jay
#

Ah, gotcha

teal yacht
#

as in cluegen vs dataclasses/attrs

#
class Op(Expr):
    op, func```
other than making the code look weird it doesn't bring anything
deft pagoda
#

you know whats weird? adding type information to python

#

i just skip that step

teal yacht
#

yeah i disagree there, but to each their own :p

deft pagoda
#

I believe that More implicit is more than implicit. the hidden kaon of python

teal yacht
#

i'm a strong believer that we should vanquish anything related to meta programming from almost every language, this kind of stuff gives me chill

deft pagoda
#

boo to you

teal yacht
#

almost every language, lisp macros get a pass

full jay
#

Dude salt where do you find these libraries?

#

clue actually looks really interesting

deft pagoda
#

uhh, well i'm a beazley fan-boy, i've watched his talks going back to, like, 96

full jay
#

Very cool

deft pagoda
#

once you watch enough of them you start dreaming in metaclasses

prisma eagle
#

@teal yacht what about rust's derive macros

full jay
#

Start huffing paint, got it

teal yacht
#

I can get behind hygienic macros in general i'd say, just the kind of stuff we see with exec/metaclasses in python is pretty eh imo

deft pagoda
full jay
#

Oooooo

#

Oh my god the title

#

That's brilliant

prisma eagle
#

async def __init__ makes me frown extremely hard

deft pagoda
#

really? because it dumps 3 days worth of dopamine in my brain

full jay
#

No pretty sure that's the paint

grave jolt
#

yeah, it's the same kind of fun as writing a Lisp interpreter in Brainfuck

prisma eagle
#

use a classmethod if you want some async work, but that's exactly the epitome of the bad idea people are trying to discourage by saying "don't do work in __init__"

deft pagoda
#

people also have no imagination

#

DONT DO ANYTHING THAT YOU MIGHT FIND ENJOYABLE

prisma eagle
#

Brian Kernighan famously wrote:

Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?

deft pagoda
#

infamously

full jay
#

I mean that's fair

prisma eagle
#

the part i find enjoyable about programming is not making something """clever"""

full jay
#

I mean

grave jolt
full jay
#

That's the point he's making

deft pagoda
#

good, keep to your side of the programming fence

gleaming rover
#

it is

#

I love coding stuff that has no practical use but is cool

full jay
#

I just can't wrap my head around that stuff

#

I'm very inside the box

prisma eagle
grave jolt
#

Actually, namedtuples now allow docstrings, default values, extra methods and type information. Default values were a thing even before NamedTuple, interestingly. That's not to say that they don't have any issues like being iterable or not being as flexible as dataclasses.

#

!e

from __future__ import annotations
from typing import NamedTuple, Sequence, Union


class SExpr(NamedTuple):
    expressions: Sequence[Expr]

class Name(NamedTuple):
    value: str

class Int(NamedTuple):
    value: int

class Definition(NamedTuple):
    expr: Expr
    lineno: int
    docstring: str = "<term>"

    def as_trace(self):
        return f"({self.lineno}) {self.expr!r} : {self.docstring}"

Expr = Union[SExpr, Name, Int]
fallen slateBOT
#

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

[No output]
deft pagoda
#

I don't think being iterable is a con

prisma eagle
#

lmao

grave jolt
#

@deft pagoda Would you be comfortable if you were iterable?

deft pagoda
#

I am iterable

#

i yield faces

grave jolt
#

C-can I iterate over you? lemon_blush

teal yacht
#

it's not a con, having it always be iterable is, however

deft pagoda
#

it's tuple, it should always be iterable

prisma eagle
#

i don't think it makes sense for tuples to be iterable in general

full jay
#

.... why?

deft pagoda
#

you what

teal yacht
#

I completely agree but eh

full jay
#

They're ordered

prisma eagle
#

consider that they aren't iterable in, say, rust

deft pagoda
#

why do we care about rust

full jay
#

What's the benefit of them NOT being iterable?

teal yacht
#

It's not just rust

deft pagoda
#

why do we care about non-python language

teal yacht
#

It's basically every ML-based languages + type theory

prisma eagle
#

that is, in fact, why i said "in general"

gleaming rover
#

i don't think it makes sense for tuples to be iterable in general
@prisma eagle from a theoretical perspective, I agree

prisma eagle
#

python uses tuples as immutable homogenous collections too

grave jolt
#

Well, in statically typed languages tuples have a more focused role; and they store heterogenous data, so it doesn't make sense for them to be iterable.

full jay
#

Different styles for different languages

deft pagoda
#

i still don't understand why they shouldn't be iterable

grave jolt
#

Like, in Python *args is a tuple

deft pagoda
#

are they not sequences in other languages?

teal yacht
#

no

prisma eagle
#

@deft pagoda they are not

full jay
#

I hate it when the argument is "it shouldn't do it because this other language doesn't do it" or "it should have it because this other language has it"

deft pagoda
#

so you can't index them?

full jay
#

It's irritating to me

gleaming rover
#

but Python has this weird tuple which is kinda list-just-immutable and kinda actual-heterogenous-grouping

teal yacht
#

you can't, salt

deft pagoda
#

then why do you want them

teal yacht
#

Well, in statically typed languages tuples have a more focused role; and they store heterogenous data, so it doesn't make sense for them to be iterable.

gleaming rover
#

you can't, salt
@teal yacht how do you define "index"

teal yacht
#

tup[2] is not valid

grave jolt
#

@deft pagoda In statically typed languages they can't be iterable because... well, how do you iterate over a (str, int, bool) in C++ or Haskell?
You can "index" them (i.e. extract individual elements), of course

full jay
#

Position in the tuple?

prisma eagle
#

@deft pagoda if we're talking about other languages this time, you can do let x = (1, 2); x.0 in rust to get the value 1 out

gleaming rover
#

you can do it in C++ and Scala, at least

deft pagoda
#

then it's a sequence

full jay
#

But we aren't discussing other languages, or should come back to the language this is about

grave jolt
#

@gleaming rover Well, in C++ you can do anything, but I assumed not using weak typing or reflection

teal yacht
#

oh, and the 0-uple and 1-uple should not exist either πŸ™ƒ

gleaming rover
#

std::get?

prisma eagle
#

@deft pagoda it's as much of a sequence as struct S { a: i32; b: i32; } is a sequence because a follows b lexicographically

deft pagoda
#

exactly

#

can you index S

grave jolt
#

0-tuple is the unit type, it makes sense if the language is expression-based

deft pagoda
#

with an integer

prisma eagle
#

@deft pagoda so, you agree: not really a sequence

deft pagoda
#

if you can do S.0 and S.1 yes

grave jolt
#

Why would you be able to do that πŸ‘€

gleaming rover
#

I don't think so...?

prisma eagle
#

@deft pagoda the x.0 in rust is a literal 0; it doesn't accept an int as an argument

deft pagoda
#

? 0 is an int

full jay
#

Cool, glad this Python server is getting derailed

gleaming rover
#

sequences and indexables don't necessarily overlap

grave jolt
#

maybe let's move this discussion to #ot-*

full jay
#

Yes

deft pagoda
#

all i've gotten from thisi s that tuples should be iterable

full jay
#

Yes you guys should

prisma eagle
#

@full jay consider that it's beneficial to talk about other languages in reference to python because you can learn from prior art. that certainly would've made the typing module less of a horrendous mess if they consulted prior art..

deft pagoda
#

this isn't offtopic --- if it's a discussion about whether some type should or shouldn't have an __iter__

gleaming rover
#

if the central discussion is tuple, fair enough, I would say...?

full jay
#

Yeah sure fine

gleaming rover
#

and honestly why doesn't it make sense to map a function over a tuple, as long as the function takes a common subtype of the tuple's elements?

#

e.g. str or the equivalent

deft pagoda
#

what do types matter

teal yacht
#

because they help proving (to an extent) your program works

deft pagoda
#

it's all PyObj

gleaming rover
#

because they help proving (to an extent) your program works
@teal yacht in this case it wouldn't break type safety, right

teal yacht
#

that "to an extent" varies more or less with the type system used

gleaming rover
#

oh

teal yacht
#

the idea behind tuples is that they can store heterogeneous elements

gleaming rover
#

not replying to me

#

never mind my bad

deft pagoda
#

that's one idea behind tuples

teal yacht
#

if you're iterating on a tuple, how would you know what type you're getting

gleaming rover
#

if you're iterating on a tuple, how would you know what type you're getting
@teal yacht common subtype

deft pagoda
#

it's not the idea

teal yacht
#

In programming languages and type theory, a product of types is another, compounded, type in a structure. The "operands" of the product are types, and the structure of a product type is determined by the fixed order of the operands in the product. An instance of a product ty...

full jay
#

Wouldn't that only apply if you're getting outside input?

gleaming rover
#

it's not the idea
@deft pagoda based on the theoretical origin (which need not be authoritative), it is

full jay
#

I mean if you're programming it, you have direct control of what the types are, where they are, etc.

deft pagoda
#

In mathematics, a tuple is a finite ordered list (sequence) of elements. An n-tuple is a sequence (or ordered list) of n elements, where n is a non-negative integer. There is only one 0-tuple, referred to as the empty tuple. An n-tuple is defined inductively using the constru...

gleaming rover
#

tuples relate to product types in much the same way ints relate to mathematical integers IMO

deft pagoda
#

this says nothing about the elements being the same type

#

for context, I'm a mathematician

full jay
#

But does say that it's an ordered list/sequence

deft pagoda
#

so, this is where my intuition of tuples comes from, not from comp sci

teal yacht
#

that article is wrong then, it lists the fact that it's a sequence as a property, then proceeds to say "Most typed functional programming languages implement tuples directly as product types,[1]"

#

algebraic data types don't come from "comp sci"

deft pagoda
#

well, fill free to edit the article

teal yacht
#

or it as much comes from "comp sci" as from "math"

full jay
#

Pretty sure it was a math thing before comp sci

grave jolt
#

quattuorvigintuple
thanks now I will use this

full jay
#

Not to say it can't be appropriated for another purpose

gleaming rover
#

what's that, 45?

#

24...

#

well, I was almost twice as correct

feral cedar
#

80 something

#

oh

full jay
#

Thought it said virgin instead of vigin

#

I'm very tired

grave jolt
#

virgintuple? πŸ€”

full jay
#

Yeeeep

#

Never said it makes sense

zealous hawk
#

VirginTuple new type coming soon

full jay
#

I think the only other argument I have about the whole tuple thing is that it's not consistent between languages. It's different for some than others

#

Doesn't make one wrong or right, just specific to that language or that paradigm

grave jolt
#

well

full jay
#

It's why I'm scratching my head as to why there was even this argument in the first place

grave jolt
#

just like all normal people arguments end with mentioning nazis, all programming discussions end at "it depends"

deft pagoda
#

another reason python is attractive to data scientists

full jay
#

More accurate to the math base?

#

@grave jolt Good ol' Godwin

deft pagoda
#

tuples are mathematical, and list comprehensions are set-builder

full jay
#

Oh huh.... hadn't thought about the latter

gleaming rover
#

quick question

teal yacht
#

i work with data scientists that don't come from CS backgrounds, and they couldn't care less about tuples being "mathematical"

gleaming rover
#

is it true that for all classes X without __setattr__ overloaded, object.__setattr__ is X.__setattr__ ?

teal yacht
#

the only reason python is so prevalent in DS is that it's easy to pick up and the snowballing effect the community has started

deft pagoda
#

that's great, let them write their piece, because "I know people" too

full jay
#

@teal yacht Is that a bad thing or...

teal yacht
#

why do you have to be so condescendent in every of your messages

full jay
#

Me?

teal yacht
#

no, @deft pagoda, "you're wrong, i'm a mathematician"

gleaming rover
#

I think the only other argument I have about the whole tuple thing is that it's not consistent between languages. It's different for some than others
@full jay I guess the thing is

#

some languages are designed with a greater focus on specific theories and paradigms

#

and some others...spring up.

full jay
#

And that shouldn't be a problem

#

Just a quirk of the lanague

gleaming rover
#

and sometimes they reinvent the wheel

#

not really a problem

#

but I can see why it could confuse others

full jay
#

Sure, fair enough

gleaming rover
#

e.g. Haskell's class is quite different from what we see in most "traditional OOP" languages

teal yacht
#

and no, it's def not a bad thing, python is popular for many reasons, the ecosystem being a large one is the main reason why i use it too, i'm just stating that it being popular because "it uses set builder notation" is a large stretch

#

haskell also has list comprehensions, and it's not popular in data science

gleaming rover
#

even though Haskell is older than I am

full jay
#

I wonder if it's older than me..

gleaming rover
#

1990

deft pagoda
#

haskell not especially readable besides the comps

full jay
#

Nope, same year then

gleaming rover
#

is Haskell even readable?

full jay
#

Not to me

grave jolt
#

Haskell is not even writable πŸ‘€ jk

gleaming rover
#

foldr
foldr1
foldr1'

teal yacht
#

no, because people are not used to it

full jay
#

Yep

#

Just takes practice and training

gleaming rover
#

it's why I sometimes wonder if Python would be better if it allowed custom operators

#

like Scala does

#

but I feel that would make it weird

deft pagoda
#

more dunders?

gleaming rover
#

and we would have Python foldr1'

full jay
#

More than it lets you over- ah okay I see what you mean

#

Doesn't quite feel intuitive or readable, though

teal yacht
#

ideally you'd just do like py def >>=(a, b): ...

#

not a dunder

gleaming rover
#

yeah, that's how Scala does it

deft pagoda
#

reasonable

gleaming rover
#

but then you would need an "all functions not starting with an alphabetical character are called with infix notation"

#

rule

full jay
#

Yep which just...

#

Yeah

gleaming rover
#

...or just + 2 3 πŸ™‚

#

map (+ 1)

#

is it true that for all classes X without __setattr__ overloaded, object.__setattr__ is X.__setattr__ ?
@gleaming rover so I'm p sure this is the case, but I'd just like confirmation

full jay
#

I have no idea

#

I'm not well versed in the meta stuff

grave jolt
#

!e

class A:
    pass
print(A.__setattr__)
fallen slateBOT
#

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

<slot wrapper '__setattr__' of 'object' objects>
grave jolt
#

ye

gleaming rover
#

yeah, that's what I did too

#

πŸ₯΄

full jay
#

Okay, quick thing. That face doesn't look woozy. Looks more like someone who just saw the person they have a crush on

red solar
#

Nah it still looks woozy for me

grave jolt
#

same thing

deft pagoda
#

just looks like a fancy mustache

feral cedar
#

@full jay isn't that woozy still

full jay
#

I suppose so

red solar
#

Scala let’s u have functions with non alphanumerical names?

full jay
#

I think I was just expecting one of the eyes to be slightly closed or something

teal yacht
#

yes, operators @red solar

red solar
#

What’s the limit on what characters are allowed in an operator name?

teal yacht
#

no idea

plucky scarab
#

I am not sure if u call this advance or not but how can I use os to rename a file but rename the oldest date modified file will be first

grave jolt
#

@plucky scarab This is not a help channel, this is a channel for discussing Python itself (read the channel description). See #β“ο½œhow-to-get-help if you want to get help.

plucky scarab
#

Sry

half drum
#

hello

grave jolt
#

@half drum
This has to do with how classes are constructed.

class A:
    def f(self):
        return A

this is fine ^ because A will only get accessed after the class has been created.
In Python, function definitions

def f():
    ...

and class definitions

class A:
    ... 

are very similar to variable assignment, like f = something or A = something.

So constructing a class like

class A:
    def f(self):
        return (42, A)

    x = 5

is pretty much the same as

A = type("A", (), {"f": (lambda self: (42, A)), "x": 5})

To create a class, you need to supply:

  1. its name
  2. its parent class(es)
  3. its "dict" -- the values to assign to a class, like f and x here.

So when you do

class A:
    the_instance = A()
    x = 5

you're essentially doing

A = type("A", (), {"the_instance": A(), "x": 5})

...and this will not work because this needs A to exist before it's created (just like x = 5 + x doesn't work unless x had some value before)

half drum
#

Thanks a lot man, trying to understand

grave jolt
#

If you don't understand some of that, feel free to ask, or maybe claim a help channel

half drum
#

Okay. Thanks! I will do that after i try

#

@grave jolt What are you doing with type() here ? isn't type(object) used to find what class the object is made from ?

grave jolt
#

type is overloaded, kind of...
let's move to a help channel, I guess

lunar panther
#

Hello, I'm trying to pack elements of a numpy array two by two in tuples : python print(array) array = pack2By2(array) print(array)
would give ```
[ 1, 2, 3, 4, 5, 6, 7]
[ (1,2), (3,4), (4,6), (7,nan)]
or
[ (1,2), (3,4), (4,6), 7]

I could implement the function pack2By2 but maybe it already exists?
flat gazelle
#

that seems somewhat similar to reshape

oak fiber
#

Please anyone can suggest me on this problem:

Problem Satatment: You are the metro corporation and you can take any steps or implement any technology in the world instantly. Today is a Tuesday and day after tomorrow ie. Thursday morning, you want to know the total number of distict passengers that traveled in the metro on wednesday. How would you go about solving this problem???

gleaming rover
#

Hello, I'm trying to pack elements of a numpy array two by two in tuples : python print(array) array = pack2By2(array) print(array)
would give ```
[ 1, 2, 3, 4, 5, 6, 7]
[ (1,2), (3,4), (4,6), (7,nan)]
or
[ (1,2), (3,4), (4,6), 7]

I could implement the function pack2By2 but maybe it already exists?

@lunar panther try #data-science-and-ml, I think

jagged tree
#

this might be a dumb question, but why don't someone take something as powerful as c++ and make it easy to use like python

flat gazelle
#

because it is not really possible. Power comes at the cost of complexity

jagged tree
#

aw

mint forge
#

Python and C++ both are high level language right?\

jagged tree
#

idk

sly bison
#

@mint forge right

heavy root
#

If only python wasnt dynamically typed

#

@compact horizon (response to dm) in a dynamically typed language you don't have to specify the type of variable

brave badger
#

Is Python's speed actually the result of it being dynamically typed, or is it because of the interpreter architecture itself in general?

half wolf
#

Both

#

@jagged tree look up nim and swift for example.

#

Python isn't really simple, it's just that simple things are simple. You can do this in a fast language.

Calling C++ "powerful" isn't very fair I think. Python is more powerful. C++ is just fast at runtime mostly, but it's less powerful in what it can express, slower to compile and slower to develop.

#

Lisps are more powerful in what they can express but quickly become confusing and messy.

radiant fulcrum
#

Pretty good summary of when to pick certain languages over another

unkempt rock
#

pretty much every modern programming language is turing complete so imo there is no point about talking which language is "more powerful"

gleaming rover
#

pretty much every modern programming language is turing complete so imo there is no point about talking which language is "more powerful"
@unkempt rock I think when people say "powerful" they generally mean "capable of expressing complex abstractions in the problem domain with ease"

undone hare
#

Is Python's speed actually the result of it being dynamically typed, or is it because of the interpreter architecture itself in general?
@brave badger the latter is because of the former, so both

flat gazelle
#

its also the fact the language lets you access very low level parts of the interpreter

brave badger
#

I may have worded it a bit incorrectly but what I meant was basically the fact that there's a bunch of articles talking about how Python is slow solely because of dynamic typing without actually going into the specifics of the CPython implementation, which I hate

flat gazelle
#

a great counterexample is something like CL and scheme

brave badger
#

That's what I'm thinking as well

half wolf
#

@unkempt rock well obviously no. We can compete in say writing a csv parser. I get to use python (but not the csv module from the standard library obviously) and you get to use brainfuck.

#

Both turing complete so it's a fair fight!

#

@brave badger agreed. But a lot of the problems pypy have in making it go fast is due to the dynamic features afaik.

flat gazelle
#

afaik, the issue is more keeping compatible with cpython impl details and the fact everything must be an object for is to work correctly

#

I mean, dynamic does not help, but there is a reason pypy is slower than V8

half wolf
#

The big reason is the amount of time and energy put into it.

#

Pypy has lots of problems with cpython extension modules yes. But that doesn't explain why pypy is sometimes not much faster when it's all native python.

half wolf
#

Javascript is fast because there are enormous amounts of R&D poured into it. Pypy is two guys with almost no funding.

coarse tundra
#

One of the softwares that we work with, cancels Python support in favour for C++ and LUA... (Personally hates LUA), reasons ... Python is slow...

empty kite
#

It's called Lua, not LUA. It's the Portuguese word for moon, not an acronym. @coarse tundra

#

I maintain a rather large OSS project written in Lua and I think the language is mostly fine, even though I would prefer it to be written in Python

#

Interestingly, the most popular third-party library for Lua, Penlight, aims to bring many Python idioms over to Lua

#

So I think many developers who don't code in Python also appreciate its language features to some degree when they encounter them in other languages

unkempt rock
#

thanks for sharing that knowledge, i didnt know

lean garnet
#

Python has too many caveats to be worth it imo. Anybody who has worked with a huge enterprise codebase in python knows how it's hell to deal with

#

Dynamic typing was cool 20 years ago, now it definitely shows its flaws

unkempt rock
#

true

lean garnet
#

I'm personally in data, and I use python cause I have to, but at home I prefer julia 100x. Python at least is not too bad as a glue language, but even for that

unkempt rock
#

where do u learn from?

lean garnet
#

what do you mean?

unkempt rock
#

i mean like python where do u learn

lean garnet
#

I learned by myself. Had a lot of prior knowledge in C++ beforehand

unkempt rock
#

oh ok u seem to be an advanced programmer

raven ridge
#

afaik, the issue is more keeping compatible with cpython impl details and the fact everything must be an object for is to work correctly
@flat gazelle everything being an object isn't an implementation detail, though, it's a fundamental language design decision

flat gazelle
#

thats why the and is there

raven ridge
#

Ah, two separate points. Ok, fair enough. The "implementation details" part is I think not particularly true when it comes to running Python code in pypy, but it definitely comes up for making CPython extension modules run in pypy

spark magnet
#

@lean garnet have you tried using type hints and mypy?

#

@lean garnet i'm also curious what caveats you mean (other than dynamic typing)

viscid lintel
#

Dynamic typing was cool 20 years ago, now it definitely shows its flaws
@lean garnet there’s no perfect language either

#

I disagree with people saying Python is slow given its flexibility

half wolf
#

Anybody who has worked with a huge enterprise codebase in python knows how it's hell to deal with
@lean garnet

Disagree. I work on a 280kloc code base. Have been for 9 years.

viscid lintel
#

even in Google there’re tons of stuff written in Python

spark magnet
#

"everyone knows X" is hardly a convincing argument πŸ™‚

half wolf
#

What IS hell is shipping code. And C++ ;)

grave jolt
#

I hope google doesn't mix camelCase and snake_case in their production code like they do in their API wrappers πŸ™‚

spark magnet
#

they use two-space indents, there's no talking to them

grave jolt
#

They're using 4 in the wrapper πŸ€”

full jay
#

Their documentation hurts to work with

#

You have to go through a maze of links to get a general idea of how to do something

grave jolt
#

I have the same experience, but thankfully I didn't need too much integration.

viscid lintel
#

only google? its more like a common practice in the industry

#

Id say its rare to find superb documentation

full jay
#

At one point I tried to make an attachment extractor so I could pull all the various junk from my email. I've had the thing since high school, so it was a bit of a mess. I spent days on it, and I still couldn't get it to work exactly right.

#

@viscid lintel A good portion of the specifically Python documentation is very clean, actually

#

Various libraries, integrations, etc.

viscid lintel
#

well they had Guido and the first crawler was written in .py iirc

full jay
#

Sure, but I'm not just talking about the official docs

#

There's been hundreds if not thousands of docs since

unkempt rock
#

i"m trying some kickstart prob. using pyhton and I need help I'm facaing some error.
most of time my code rejected due to some Runtime error.(shown by kickstart)
its working fine in terminal and other editors but on submitting it on kickstart my codes show runtime error most of time.

full jay
#

@unkempt rock Unfortunately this channel isn't really meant as a help channel. You'll likely have better luck using our help system. See #β“ο½œhow-to-get-help for more details

viscid lintel
#

indeed improving documentation is a good way to contribute and maybe get a free tshirt in hacktoberfest

grave jolt
#

"fix typo in docs" is my favourite commit type

full jay
#

I mean it's a good and important part of a language's ecosystem in general, t-shirt or not

#

I think a lot of other languages could use some TLC in their docs as well as with any libraries associated with them

#

Python's just lucky because the idea of clarity and readability is ingrained in the folks who love it, and that trickles down even to their docs

raven ridge
#

Doc fixes are also a great way to learn how the project manages contributions, which will make things much less difficult if you want to contribute something more involved later

swift imp
#

Is there an annotation to indicate that a class method should return a subclass instance of that class?

spark magnet
#

@swift imp wouldn't you annotate that as -> ThisClass ?

#

(an object of ThisClass)

peak pollen
#

Might have to be in quotes -> "ThisClass"

#

At least until postponed evaluation is a thing

#

If the return value could also be an instance of a subclass of ThisClass, I believe it'd be -> Type["ThisClass"]

swift imp
#

Yes

#

the return WILL be an instance of a subclass of ThisClass

#

Perfect

#

Thank you

peak pollen
peak spoke
#

Type will mean it expects the actual class object to be passed in, not an instance iirc. Just ThisClass should also include all subclass instances

peak pollen
#

oh!

#

Yes that's my bad, misunderstood

swift imp
#

Wait so

peak pollen
#

To clarify, it's what nedbat mentioned earlier, just wrapped in quotes

swift imp
#

Just return ThisClass

#

ok

spark magnet
#

you don't need quotes if you use a new enough python, or a from __future__ import annotations import

peak pollen
#

TIL

#

Something later than 3.8.2?

raven ridge
#

That won't be the default until 3.10, AFAIK

swift imp
#

Good to know

swift imp
#

Inheriting from class foo(abc.ABC,meta=CustomMeta) allowed or bollocks?

grave jolt
#

Is there an annotation to indicate that a class method should return a subclass instance of that class?

class Parent:
    @classmethod
    def make(cls) -> Parent:
        return cls()

^ this means that for any subclass Child of Parent, make will return an instance of Parent, not necessarily an instance of Child, which is probably not what you want.
This is how to fix it:

P = TypeVar("P", bound="Parent")

class Parent:
    @classmethod
    def make(cls: Type[P]) -> P:
        return cls()

Now Child.make() is identified as Child, not Parent.

#

@swift imp ^

swift imp
#

Ty

gleaming rover
#

do you think there will ever be another way to specify type parameters

#

this TypeVar thing is honestly so ugly

#

and verbose

swift imp
#

Initializing a subclass instance during __init_subclass__ is that possible given the mro or no?

grave jolt
#

@gleaming rover Well, one way would be to just use strings, I suppose.

undone hare
#

generics when

#

Can't you already make generics though?

#

I remember seeing something similar

spice pecan
#

You can indeed do generics with TypeVar

cloud crypt
#

PEP 638 anyone?

#

was waiting for it for so long, haha

magic python
#

@cloud crypt when would you use that?

cloud crypt
#

let me link that first

#

!pep 638

fallen slateBOT
#
**PEP 638 - Syntactic Macros**
Status

Draft

Created

24-Sep-2020

Type

Standards Track

cloud crypt
#

alright so

#

one use I have is code generation that can be very nifty at times

magic python
#

what does nifty mean in this context

visual shadow
#

Sounds like one of those things that's above my head. Also sounds quite powerful

brave badger
#

Interesting, I'll give that a read later

visual shadow
#

Am I correct in understanding that it's essentially designing a mechanism for code substitution before compilation? Not so much so as a concrete use case, rather a feature that enables people to create their use cases from code substitution?

gleaming rover
#

wait SERIOUSLY?

#

macros in Python

radiant fulcrum
#

i mean you can achieve code generation using exec which is what most if not all code generators use todo so

#

what most Python 2 and Python 3 compatible packages do to dynamically change depending on the python version

magic python
#

i have no idea what it's about still but if anyone has a basic example of what a macro is in this context and why/when it's useful that'd be appreciated

brave badger
#

tl;dr macros basically generate code before runtime. They're especially useful for abstracting routines with little to no runtime cost afaik.

magic python
#

what are opinions on assert statements? I've only just read (https://stackoverflow.com/a/9626854/3130747) that they get removed at some point, so are they just meant to be a temporary helper for the developer rather than ensuring the proper types are passed to functions? Bc sometimes I'll have ~4 assert statements at the top of a function, which makes me feel as though I'm doing something wrong now

peak spoke
#

Do you need those asserts? They're intended for tests etc.

magic python
#

It's for usage though - I know it'll break, but wanted a useful message if the wrong value is passed

#

If they were all moved to unittests, then I could run pytest or whatever and make things ok, but someone could still pass in an array which will fail with the function. Maybe people just let things fail the way they fail? Seems less helpful than giving a particular message for the problem though

grand furnace
#

you can always raise custom exceptions

magic python
#

so instead of 4 asserts in a function you'd have 4 raise ValueError( ... ) or similar?

grand furnace
#

yes

magic python
#

that makes sense

peak spoke
#

Validating inputs if it helps wouldn't be a bad use case, but feels like it would make the code a lot more noisy. The expected arguments should be documented and if the user passes something that doesn't use that, that's their problem. The assert mainly shouldn't change the logic of the code since they will be excluded in compilation with optimize flags

magic python
#

The expected arguments should be documented and if the user passes something that doesn't use that, that's their problem
Yeah, that also makes sense. Hrm, they do feel messy

grand furnace
#

I'd say that's not a hard rule

magic python
#

raising custom exceptions would be even messier i guess, if not condition: raise <exception>

grand furnace
#

For instance if a function takes in a data object but the function requires that the element x be a specific value if element y is a specific value a custom validation exception fits

#

That type of pattern is used a lot in web apis

magic python
#

i have some things checking that the dimensions are correct, eg matrix has >2 columns and stuff. So, that could be put in the documentation, or it could be done with assert <all rows have same number of elements>, "blah", and it's not clear to me that the latter is worse than the former

half wolf
#

@magic python asserts are removed if you use -o yes which is weird and no one uses it. Asserts to check invariants is perfectly fine imo. I use it all the time.

magic python
#

fair - just checked out numpy does some of it - they use stuff like :

def _assert_2d(*arrays):
    for a in arrays:
        if a.ndim != 2:
            raise LinAlgError('%d-dimensional array given. Array must be '
                    'two-dimensional' % a.ndim)
half wolf
#

As long as the error message is very good I don't think the type is very important. Unless you do want to handle it obviously. All problems that are for dev time can be asserts.

magic python
#

yeah, and in pandas they have

    def _get_grouper_for_level(self, mapper, level=None):
        assert level is None or level == 0

etc... hrm, I guess it's just subjective - I don't think I like having them in the documentation as much as the code

#

docs are easier to rot for me at least

half wolf
#

Yea. Executable > not executable.

cloud crypt
#

it’s that

#

AssertionError is not really suitable for library code imo

magic python
#

@cloud crypt seems subjective, and I haven't really seen a clear example of why it isn't having searched a bit. Other than it being dropped when running -o at least

peak spoke
#

The type also isn't very descriptive

cloud crypt
#

yeah

#

TypeError or custom error can be much better

magic python
#

i fail to see how something like

def check_dim(A):
    if A.shape[1] < 2:
        raise ValueError("Array requires at least two columns")

is much better than

assert A.shape[1] >= 2, "Array requires at least two columns"

I'm probably missing something

cloud crypt
#

eh

frozen abyss
#

Hello,
I found this little explaining text on a python project and I wonder how it works:

clients never write anything to the disk - not even temporary files (zero IO system calls are made) because remote imports allow arbitrary code to be dynamically loaded into memory and directly imported into the currently running process
Anyone can help to perform this ?

hollow crane
#

if you want to load a custom module, you don't have to save any files to disk then load them

#

because you can load a module directly from the code in memory

#

not from a file path like with import or __import__

half wolf
#

@cloud crypt asserts are much better if it's mostly for errors done while developing. That goes very much for libs.

#

Raising a specific exception can be worse because it can be caught incorrectly too.

sacred tinsel
#

I've worked on a project where developers used asserts a lot as sanity checks that eventually made it into "production" (maybe not a good word because the product was transformed data, not the code itself), I don't have any strong feelings about it as long as everyone is aware that -O will ignore them

#

At the same time I'm not aware of -O even being used anywhere, but maybe that's my ignorance

half wolf
#

Yea, -o should be removed. If you want faster python, write an extension, don't just delete asserts.

magic python
#

@cloud crypt sure eh but you've not actually given anything concrete, just preference, hence me assuming that's all it is, preference

gleaming rover
#

Yea, -o should be removed. If you want faster python, write an extension, don't just delete asserts.
@half wolf it also sets __debug__ to False

#

I don't actually use it but I can kinda see the use case

cloud crypt
#

AssertionError has those test vibes

peak spoke
#

I use -OO regularly when distributing apps, It's not exactly python's best use case but the flag does help with it

cloud crypt
#

eh it doesn’t really give speed anyway

#

just decreases size in a simple way

half wolf
#

Yea it's like "optimize!" and then it doesn't really.

#

@gleaming rover hmmm... Yea well. For example django has settings.DEBUG instead because that thing isn't useable as we've established.

cloud crypt
#

yeah definitely

#

well, removing docstrings really does optimize your size

lofty rover
#

For envinonment management in WSL, venv or conda, what do you recommend?

sacred tinsel
#

I like pyenv with pipenv, works great for me

patent charm
#

None of the above, just docker.

sacred tinsel
#

pipenv builds on top of virtualenv

#

conda is probably good on windows, some of my coworkers like it

carmine lake
#

Speaking of environment I always use pipenv and virtualenv (venv)

autumn harbor
#

I'm not sure if beautifulsoup would be advanced? Can someone help advise if I should be posting my question about beautifulsoup here or in the general channel?

sacred tinsel
#

If you're looking for help, either a help channel or perhaps #web-development if you feel like it's appropriate would be better places

#

This is more for discussion

autumn harbor
#

Perfect. Thanks @sacred tinsel

sacred tinsel
#

no worries

autumn harbor
#

I'm using it in my python program. Does that change things?

sacred tinsel
#

no, that just means you're in the right server

autumn harbor
#

Word.

fiery cradle
#

I need a help

A array is given consisting of A ones and B zeroes

We have to select C elements from array, delete them from array and append their average in fraction form to the array

At last only one item remains in the array

Input:
A:1
B:1
C:2

Output: 1

The array is [0, 1] I have to take 0 and 1 and delete them and add 1/2 to the array

Input:
A:2
B:2
C:2

Output: 5

There will be 5 possible values 1/4 , 1/2, 3/8, 5/8, 3/4 and at last only 3/8 will left

Delete 0 and 1 and append 1/2 to the array
Delete 1/2 and 1 and append 3/4 to the array

Delete 0 and 3/4 and append 3/8 to the array

#

Please help me

feral cedar
red salmon
#

anyone know how to write the function total gpe in a 2d system for π‘ˆπ‘—π‘˜=-πΊπ‘€π‘—π‘€π‘˜/π‘‘π‘—π‘˜, where user inputs the number of grid-points in a system where they are spaced 1 meter from their neighbor?

cloud crypt
#

this is not a help channel

red salmon
#

ahh, my b

boreal rune
#

wouldnt it be way more memory efficient for python to draw methods from the class itself instead of giving every object their own individual copies of each method?

peak spoke
#

Methods are looked up at the class objects from the MRO, they're not attributes on the instance object

boreal rune
#

oh Huh

#

alright

swift imp
#

Anyone have advice on a pattern where the parent captures an instance of the child upon definition? I was going to do this in __init_subclass__ but realized its way too early, and not possible because still have to go through __new__

flat gazelle
#

No instance exists at definition

swift imp
#

Ok, maybe after definition?

#

I realize I cannot do it during __init_subclass__ but can I do it in another dunder?

flat gazelle
#

If you want to log instances at creation, put a weak ref into a list in __init__

swift imp
#

No I don't want to log instances at creation. I just have a need to store child instances, in the parent, after they're defined.

#

Maybe it will just easier to store the module and name of the child, I can do that in __init_subclass__