#internals-and-peps

1 messages · Page 122 of 1

visual shadow
#

there's a certain simplicity to python's view. again, to emphasize, everything is an object in python

flat gazelle
#

yup

#

keep in mind an int is unbounded

coarse urchin
#

Right

flat gazelle
#

so not like you can do much about that

#

but it holds for floats too

coarse urchin
#

I assumed that maybe it could be by default an int and then if exceeded to go to unbounded integer

visual shadow
#

nope. not in python

coarse urchin
#

I see

undone fable
#

Like how it's stored in the underlying runtime

#

Are ints stored as bigints as in other languages?

visual shadow
#

you can always mix python with lower lvl languages like C for certain portions, with lower level semantics as you preferred

#

however, from the perspective of pure python, there's no concept of memory management*, it's abstracted away

coarse urchin
#

Yeah, I know, I was just curious about what we get as the core thing of python

#

Thanks

undone fable
coarse urchin
#

Pig, why are you trying to lose friends again (jk)

undone fable
coarse urchin
#

Even despite being bounded

flat gazelle
#

yes

#

you can even look at the object in the cpython source

coarse urchin
#

I was just thinking... that with big caches and stuff today, we could theoretically afford 16-byte long primitives, with 8 byte for data and 8 byte for type

#

So that <= 8 byte long primitve data structures could be stored as value types

#

And everything else would go as reference type

#

Do you think it would be much more efficient that what we have in python now?

flat gazelle
#

less pointer chasing would help, but would it help enough to be a measurable difference, idk.

coarse urchin
#

It would give much less garbage and much more direct computations (=> caches and stuff work)

#

Although the 1st statement comes from my own thoughts, I have no idea how exactly memory management works in python

flat gazelle
#

at the same time, you still have an indirect call with accessing the type and reading its slots to know what operations to do

#

so I am not sure just copying around less would matter all that much

coarse urchin
#

I store the tpye info in the value itself

flat gazelle
#

you can't fit a python type in 8 bytes

coarse urchin
#

... why?

flat gazelle
#

types in python have so called slots, which define what happens on various operators, such as +-*/.

coarse urchin
#

But doesn't pyython runtime treat built-in primitives like floats its own way?

flat gazelle
#

no

coarse urchin
#

Hm

flat gazelle
#

they are still just objects, with an extra float field and the type is responsible for using the field effectively

coarse urchin
#

But each float stores a reference to some type meta data, right? Including the slots

flat gazelle
#

some things do optimise by checking if the type is the native type and skipping the indirect call, but all objects in python have a common interface which is what most of python uses

#

a python object is a refcount, the type, and then whatever values are needed for the object

coarse urchin
#

some things do optimise by checking if the type is the native type and skipping the indirect call,
Well that's what I thought to use my unions for

flat gazelle
#

but you don't get the not specialised option then, right?

coarse urchin
#

Yeah, i don't

grand cypress
#

Hello! I am creating a raw tcp socket and sending a crafted ip+tcp packet (it works, i can see it in wireshark), but when I try to recv on the socket, I get: [errno 11: resource temporarily unavailable]. Pseudocode in python: http://pastebin.com/khgefa0Z  am I missing some syscall or socket option?

flat gazelle
#

are you familiar with java? Because let me tell you, having to special case your code for every single primitive type is not fun

coarse urchin
#

So generally, (a + b) would be 2-3 indirected call?

flat gazelle
#

especially in python, where you optimise specifically floats and absolutely nothing else

flat gazelle
#

yeah, C# has a more sensible implementation of primitives which lets you be generic over them

coarse urchin
#

C# is statically typed, so we don't have anything like that

#

(technically there's dynamic, and it doesn't work on unions either)

#

But yeah, with int being unbounded, I believe I would only optimize floats

flat gazelle
#

well, a + b is

load a (possibly from the local scope, which are static)
load b (possibly from the local scope, which are static)
call the add opcode
```the add opcode then checks the add slot on a, if it gets `NotImplemented`, it check the radd slot b, and then call that
#

so it is 1-2 indirect calls and a lot of pointer chasing

coarse urchin
#

load a is one indirect call, load b is another one, and checking for a's add is a third one, right?

#

So 3-4 indirect calls

flat gazelle
#

loading from the local scope is an array access, but a global scope would indeed be an indirect call

coarse urchin
#

Oh, that's fun. So it's some kind of indirect stack?

#

"local scope is an array access"

flat gazelle
#

local scopes are static, so the frame can just keep an array of objects and the compiler converts local accesses into indicies (though the names are still kept so that eval and exec work)

#

but you can't add a new local with exec

coarse urchin
#

So, do I understand it right:

b = ... # local var
c = ... # another local var

a = b + c

<=>

*a.ref = add(*b.ref, *c.ref) # pseudo code showing how we load the values and try to add then

<=>

arr[2] = add(add[0], add[1])    # "dereferencing" replaced by a local static array

right?

flat gazelle
#

more or less

#

!e
you can even look at it

import dis
dis.dis(lambda a, b: a + b)
fallen slateBOT
#

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

001 |   2           0 LOAD_FAST                0 (a)
002 |               2 LOAD_FAST                1 (b)
003 |               4 BINARY_ADD
004 |               6 RETURN_VALUE
coarse urchin
#

Oh I've seen that API, is it JIT for python, right?

flat gazelle
#

no, that's just bytecode

#

all cpython code goes through this

coarse urchin
#

Oh

#

So that's more or less what I wrote, right?

flat gazelle
#

yes

coarse urchin
#

Great. Thanks

opal meadow
#

why does this work the same?```py

raising an error class

raise type('TestError', (Exception,), {})

raising an error instance

raise type('TestError', (Exception,), {})()

sacred tinsel
#

if you raise the class, it will be instantiated without args implicitly

#

so raise Exception and raise Exception() should be functionally equal

opal meadow
#

o

magic python
#

i was just bumbling around some code, right clicking go to defn to go to the source etc, and realised that I was actually reading code for the inspect module, not the package i was intending to read.

I'm aware (i think?) that some core python modules are written in C, some are in pure python etc... But i'm not sure if there's any logic to what's written in which and why. For example, why is the inspect module not written in C? (Or cython, or whatever).

Given a random module from the standard library, can one say what the source would be written in given the module and it's purpose? Or is it just whatever the author felt like / was familiar with?

cobalt agate
#

If anyone wants to code together on it please get in touch

magic python
#

@cobalt agate i don't think this is the right channel for that, if you had a specific question about classes / their use it might be more suitable, going through your code and refactoring is probably off topic though

verbal escarp
#

imo classes should not be used just for the sake of using classes.

#

i think one should use classes for two reasons - bundling same things together (data or functions) or to deal with state

#

making APIs nicer maybe can be third reason, but that's more advanced

#

more often than not turning nicely defined global functions into methods leads to the temptation of introducing side effects via self

#

only making testing more complicated without offering much of a benefit

#

the most straight forward way to hoist functions into a class is by using @staticmethod for simply grouping functions together

cobalt agate
verbal escarp
#

it is a decorator, yes

#

builtin

cobalt agate
#

I will look that up. Thanks for the tip. If you get a chance to look at tonmiles.py I'd greatly appreciate any more pointers you have.

verbal escarp
cobalt agate
verbal escarp
#

btw, this doesn't look like a toy program, is that actually deployed?

cobalt agate
#

Deployed as in? I haven't bundled it in an exe yet but it's good to go
Works perfectly

verbal escarp
#

on an oil rig?

cobalt agate
#

Calculates tonmiles for the day and stores data in a csv file

halcyon trail
#

Fwiw in python it's pretty rare to use @staticmethod

#

Not never, but it's not usually the first choice

verbal escarp
halcyon trail
#

Why's that?

verbal escarp
#

because, as i said, it avoids the temptation of using self for side-effects

#

while keeping the benefits of bundling

cobalt agate
# verbal escarp on an oil rig?

Yes. This brief thread will explain what the program does. If you're interested.
https://twitter.com/zubin_madon/status/1413821733732175872?s=19

The rig floor on an oil rig is a dangerous place to be. 100's of tons of steel goes up and down the length of the mast at breakneck speed. Roughnecks work standing directly under this, tripping pipes in and out of the hole, in 12 hour shifts. #100DaysOfCode #thread. https://t.co/IJgErB5Ybv

halcyon trail
#

There's already a bundling mechanism

#

Packages/modules

halcyon trail
#

That's their job

#

Classes are for managing state

#

Idiomatically it's somewhat common to see class or static method for "named constructors" but outside of that I rarely see them

#

Just use a free function in the same file as the class

#

Java made these mistakes so that we could avoid them 😃

cobalt agate
#

@verbal escarp I used a lil decorators to clear the frame of widgets when toggling from one functionality to another. But I haven't updated that bit on git. Right now I just call the clear widgets function normally within the other functions.

verbal escarp
cobalt agate
halcyon trail
#

In a decent size program there's going to be state to manage

#

So probably there will be good opportunities to use classes

verbal escarp
halcyon trail
#

But honestly don't use them just to "group" stuff

#

Well, you know, or start with what's consensus and idiomatic for a particular language :-)

#

You could look in the standard library or in major python libraries and count static methods

#

Compared to free and member functions

#

And those numbers will help you arrive at conclusions 😉

verbal escarp
#

it's debatable whether it's idiomatic, i've seen all each approach in various cases

#

there are arguments for and against each

cobalt agate
halcyon trail
#

Like I said, I would simply suggest counting

verbal escarp
#

counting doesn't help for specific cases

halcyon trail
#

No, but it will give you a sense how high the threshold is for it to make sense

cobalt agate
#

So this is what the program is. Each tab drilling, tripling, casing displays a whole new set of widgets on the center frame

verbal escarp
cobalt agate
#

As you toggle the previous widgets get destroyed and new ones appear. Then you add parameters and click calculate button

verbal escarp
#

looks very oil rig ;D

cobalt agate
#

So it calls a calculation function which is nested within the drilling function which had all the UI widgets

halcyon trail
#

If in every library you look at, static functions are only a few percent of functions, and in your library they're 50 percent, unless you really know what you're doing, you're probably headed down the wrong path

cobalt agate
#

Then the calculations are done and thrown into the bottom frame where the totals for the day are.

#

Then you click commit days data to csv which triggers another fucntion that does the pandas work

signal tide
halcyon trail
#

A general comment, I havent looked at your code so I'm not saying you're using static method that often

cobalt agate
#

Well my aim to refactor was to just practice classes. I assumed that a program which has so many different fucnctions and yet uses the same tkinter UI could use classes. Like tkinter could be a parent class where all buttons and widgets exist

halcyon trail
#

Mostly I'm just saying,functions are the simplest and most common abstraxtion in python. Classes are great too but they are more complex, it's fine to use them of course but you should know why you are using it, and have a good reason

#

It's tricky because when you approach it as "I wanna use classes" it'll be easy to overuse them :-)

cobalt agate
signal tide
halcyon trail
#

For classes I would probably start by considering related state, rather than related functionality

flat gazelle
#

for comparison, django has 61 static methods and 1600 free functions

halcyon trail
#

Like, thesrntwo variables are intimately connected, when I modify one I want to also modify the other

verbal escarp
#

@cobalt agate btw, try to avoid * imports, they mess with IDEs and your head down the road

cobalt agate
signal tide
#

there's a time and a place for them, just not for namespacing ¯_(ツ)_/¯

#

actually isnt there a namespace metaclass somewhere?

halcyon trail
#

Well it's really more about code than UI snapshot

#

There is

signal tide
#

where

halcyon trail
#

It's used as the return from argparae

#

Argparse

signal tide
#

I thought typing had something similar but I cant find it

peak spoke
#

types.SimpleNamespace?

signal tide
#

typing/types same difference 😄

cobalt agate
flat gazelle
#

at the same time, UIs are generally where classes make sense

#

esepcially considering your program starts with 6 globals that would work great in a class

verbal escarp
halcyon trail
#

@flat gazelle agree that members are better than globals

#

But then you would need instance methods

cobalt agate
halcyon trail
#

Not static methods

fast smelt
grave jolt
#

I once made a horrible namespace hack that allowed you to do ```py
@namespace
def foo():
def bar(x, y):
...

baz = ...

class spam:
    ...

```, and it would make foo into a namespace with names bar, baz and spam. Can't find the source now, but you can imagine how hard it messed with editors

flat gazelle
#

yeah, using static methods is definitely wrong here

#

half of these functions use shared state

cobalt agate
verbal escarp
#

@halcyon trail i can easily think of classes that have no state at all but also don't make use of staticmethods 😉

#

@halcyon trail for instance abstractions via properties

undone hare
flat gazelle
undone hare
#

Haha

grave jolt
flat gazelle
#

whether you want to move all the UI elements into a class is up to you

halcyon trail
#

Yes, there are all kinds of uses if classes without state

#

Metaclasses too!

#

But that is more advanced

grave jolt
halcyon trail
#

The starting point should be that classes are for managing state, that's their original and most common purpose

cobalt agate
halcyon trail
#

@grave jolt mutable or not

flat gazelle
cobalt agate
flat gazelle
#

yeah, going from passing around globals to full separation of concerns takes a while

fast smelt
#

like does it send the email and password I put in the cmd will be sent to someone?

flat gazelle
#

@fast smeltthis project is in violation of MS and mojang TOS I am pretty sure, so we can't help with it

cobalt agate
fast smelt
#

in game development?

flat gazelle
cobalt agate
#

Thanks @flat gazelle very helpful pointers. Now the herculean task of putting all this in practice.

flat gazelle
#

the other way is also possible, but keeping the computation class clean of UI allows you to write tests

cobalt agate
#

The tkinter button has a command kwarg which triggers a function. One of the calculation functions. However the calculated result has to go in a tkinter widget again to be displayed. So the calculator function will either have to have a label.config call in it to change the widget, or it must return a value which some other function uses to change the result widget.

#

So it is hard to completely separate both

visual shadow
#

let it return. that's how it's separated.

#

essentially the function should act like it doesn't even know about tkinter.

flat gazelle
#

I don't think a return will work here alone
how about making a callback that will run the calculation class, get the result from it and display it where it is meant to be seen

#

this callback is part of the UI

cobalt agate
#

This is a lot to chew on. Lol.

visual shadow
#

basically, think of it like an onion. your topmost function/callback whatever is responsible for being invoked from the UI. then, it talks to your class/functions inside to do some work. anything inside doesn't know about the stuff outside. so, the UI becomes the topmost layer, the function being called from the UI is just sitting underneath, and your core business logic is inside.

cobalt agate
#

I guess it will need 3 steps.
Button(command= function1)
Function1() :
Calls variable = calculator()
Puts variable in label.config(answer is 'variable')

visual shadow
#

so, the outer layers use the inner layer, sure. but the inner layers don't need to know about who called them or why.

cobalt agate
#

Thanks a lot everyone. You've given me a lot to think about.

#

Appreciate it v much. If anyone is bored enough to work on this together plz msg me and I'll be glad to work around your free time :)

verbal escarp
#

you're welcome, don't hesitate to stop by if you need more advice/opinions 😉

valid rose
#

how do you add dunders on classes?

#

i don't mean objects, i mean the class itself

spark magnet
valid rose
#

__getitem__

native flame
#

there's a __class_getitem__ coincidentally

valid rose
#

whaaaaat

#

TIL

native flame
#

for other dunders you'd need a metaclass i suppose

#

also

spark magnet
#

if you don't mind me asking, what will you use it for?

native flame
#

if this is for typehinting you should probably inherit from typing.GenericAlias(?)

valid rose
magic python
#

is there a way to get the falsy value given an instance?

eg:

f([1, 'a', (1,2,3)]) -> []
f(3) -> 0
f('hello') -> ""
unkempt rock
magic python
#

@unkempt rock yeah i was wondering if there was a way to get the falsy value from something though, i guess you just have to check a bunch of isinstance ? and return appropriate from that

unkempt rock
#

type(3)() -> 0

#

What's the usecase?

verbal escarp
#

got bitten hard by assuming empty instances always default to falsy

magic python
#

i was just curious really - well - i made something that would split lists into n chunks, then i wanted to pad the last sub-list (which would have fewer elements typically unless len(list) was divisible by n). I thought maybe I'd pad with the falsy value of the list def f(input_list : List[T], n : int) -> List[T] was what i'd typehinted with...

then i realised i wasn't sure how to do it

#

using type( ... )() makes sense tho : )

unkempt rock
#

That isn't obeyed by any arbitary object though

class Foo:
    def __init__(self, name: str):
        self.name = name
``` for example
magic python
native flame
#

padding with Nones might make sense

magic python
#

yeah that'd be fine

halcyon trail
#

Just out of curiosity, what's the reason to pad? Will later code assume that the lists have fixed length?

halcyon trail
#

The downstream code will either have to watch out for shorter lists, or for None-padded lists

#

I see

#

Personally I would probably have the chunking function not pad the list, and handle that issue further downstream

magic python
#

use case is pretty basic - it's mainly just for quickly looking at what columns are in some data

halcyon trail
#

But maybe the opposite makes more sense

#

I see

#

Usually use a lot of pandas stuff for that sort of thing

magic python
#

yeah if you have a df with a lot of columns i'm not sure what the most straightforward way to see them all in a table is

halcyon trail
#

Pandas data frames have a bunch of methods to help with this

magic python
#

like what?

halcyon trail
#

You can create an html table automatically from one

#

Or just a regular text table

magic python
#

i'm aware pandas dataframes have a bunch of methods, but i'm not aware of a method that will enable you to see all 200 columns in a table easily

halcyon trail
#

I mean just doing print(df) will give you a reasonable representation if it's not too big

magic python
#

nope - too big

#

which is why i want them in a table

halcyon trail
#

I'm confused, the table is just the visual representation of a data frame?

magic python
#

no - it's only the columns, just to have a quick gander at what the columns actually are

#

sorry - only the column names (that was confusing)

halcyon trail
#

But just the columns are a list, not a table, right?

#

Do the column names have some additional organization

magic python
#

yes, well a pandas index, but a list yeah

magic python
halcyon trail
#

So basically you want to print a long list in a readable way by breaking it up into sub lists?

magic python
#

yeah that's all, i mean - i have something that does this, and use it - i was just messing about when i thought of the type thing previously

#
def ltt(*, lst, cols=7):
    ar = np.array(sorted(lst))
    rows = int(np.ceil(len(ar) / cols))
    ar.resize((rows, cols), refcheck=False)
    return pd.DataFrame(ar).replace({0: ""})

this is what i usually use - maybe there's a more obvious approach idk

halcyon trail
#

Could look at pprint as well

magic python
#

pprint doesn't do it really

halcyon trail
#

Because they're not aligned?

magic python
#

just doesn't give an output that's nice to read like the above

slow acorn
#

what does ltt stand for?

magic python
#

list to table

slow acorn
#

why not spell it out?

magic python
#

why spell it out when i know what it means?

slow acorn
#

presumably you posted it for others who won't know what it means

halcyon trail
#

I guess I was confused for a while because table usually implies some relationship between rows and columns

magic python
#

oh sorry - i thought it was obvious from context, didn't think about others than quick reading it there

halcyon trail
#

Whereas this is an aligned list

magic python
#

that's just a copy paste, didn't type it out

halcyon trail
#

I think I see now though

magic python
#
In [10]: lst = ["".join(np.random.choice(list(string.ascii_letters),3)) for _ in range(50)]

In [11]: ltt(lst=lst)
Out[11]:
     0    1    2    3    4    5    6
0  BTU  BoO  Bsx  Cta  Cut  DHT  EGR
1  Eah  HAn  Hiy  JDG  JJz  KVg  LDY
2  MuF  MwN  NYG  PrB  Qna  Tdp  URO
3  VLa  VyN  XeB  ZHk  aCL  dCH  eCO
4  eNj  gkZ  hSl  hYx  hcb  iWU  jAA
5  ldK  mNf  nkT  oIU  pMO  qUc  qzv
6  rPZ  rdD  ruz  utZ  wJm  yaz  zAL
7  zlK

in case it was unclear, not important though

#

i find it helpful sometimes, but only use it during eda

halcyon trail
#

But why have the numbering of rows columns out of curiosity

#

I can understand the alignment for readability

cobalt agate
#

In context of our discussion a few hours earlier, Composition Vs Inheritance: https://youtu.be/wfMtDGfHWpA
@verbal escarp @flat gazelle @halcyon trail @visual shadow the person in the video makes a compelling case to NEVER use inheritance. Would you agree/disagree with his rationale?

💖 Support the show by becoming a Patreon
https://www.patreon.com/funfunfunction

This is a weekly show where we try to become more confident and excited about programming by learning intriguing things that we didn’t know before. Today, we are are going to talk about composition over inheritance. Inheritance is when you design your types after wh...

▶ Play video
verbal escarp
#

disagree.

visual shadow
#

never is a strong word.

#

however, there is benefits to preferring composition. haven't seen the video, but GOF recommends composition too, if that's any benefit

verbal escarp
#

i'd prefer composition in most cases, but inheritance has its values

cobalt agate
verbal escarp
#

hm.. it's not that simple. in python syntax and functionality revolve around protocols, often one or more __method__that is accessed to implement stuff

#

so, if you want to check if an object can be multiplied, you could check for __mul__

#

but that quickly becomes cumbersome the more methods are involved to implement a protocol

#

there you can use classes to signal "yeah, you could check my methods or just believe me when i say i'm a context manager"

#

so instead of checking what an object can do you'd check what an object is

#

of course, you could still add or remove functions in python independently, but let's try to stay civil ^^

#

so yeah, if the example is as simple is "can bark, can poop, can drive" it's easy to check for those abilities

#

but if you look at GUI frameworks especially like PyQT, there can be hundreds of methods

grave jolt
#

well, you could argue that an interface that consists of hundreds of methods isn't a good idea in the first place

verbal escarp
#

it's not a "good idea" but it's the reality

grave jolt
#

not saying it isn't 🙂

flat gazelle
#

inheritance works out nicer if you need a subclass to only provide one or two methods, whereas with composition you can't really have a model of "A is B, but C". You can still express the same things, but composition can end up messy as relationship between traits grow in hard to document ways, where inheritance tends to be a simple tree (even if python will let you have other shapes in it).

signal tide
#

Entity Component Systems are a good example of where composition thrives tho, in a sense you need the messy relationship that data-driven systems provide because any sort of rigidity can end up meaning more complexity/redundancy

flat gazelle
#

yes, I would argue that composition is overall a nicer way of modelling data and behaviours, but general truths lose to specific circumstances

halcyon trail
#

@cobalt agate it really depends, it depends on circumstance

#

It is true that in general, implementation inheritance is far more discouraged now

#

Even OO languages are discouraging implementation inheritance

#

And it's also true that python doesn't really need interface inheritance the way that statically typed languages do

#

So, overall I do use inheritance in python very sparingly

flat gazelle
#

yeah, most of my code is composition or even just full on dynamic polymorphism without a common protocol

halcyon trail
#

When I use polymorphism I usually have a common interface

#

But you can do that with protocols, you can also register classes into ABCs so it's not quite the same as inheritance

#

Etc

flat gazelle
#

pretty much

    def selected_tile(self, selection):
        if isinstance(selection, int):
            return self.sides[selection]
        elif isinstance(selection, tuple):
            return self.board[selection]
```is what I do most often
halcyon trail
#

I do still use ABCs and inheritance of them in python but they aren't required

cobalt agate
halcyon trail
#

Compared to Java, C++ etc where using interfaces is basically mmandatory

#

Yeah, it might be

#

Honestly I maintain a good amount of python code and it's mostly extremely simple

verbal escarp
halcyon trail
#

Mostly functions and data classes, some normal classes, even fewer inherited classes, etc

#

I've probably used reflection in python about as much as inheritance 😃

#

Reflection actually solves real problems that you can't easily solve another way without a lot of boilerplate

flat gazelle
flat gazelle
#

or well, I have used inheritance to use certain libraries that require it, but for actually modelling my own code, very rarely

halcyon trail
#

It will be cool if more languages have delegation as a first class feature

#

Achieves the things you often want to do achieve with implementation inheritance

#

Without the pitfalls

#

I also really recommend googling and reading about the fragile base problem

#

Its one of the main reasons for the fall from grace of implementation inheritance

cobalt agate
verbal escarp
#

prototypes are another approach

halcyon trail
#

If you want to reflect over data I recommend starting with dataclasses

#

That's been one of my main usages. Having code that can serialize any data class the way I need it serialized, using reflection, it's very nice

#

And much more organized, just poking into raw dict members can be a bit hazardous

grave jolt
#

there are also libraries like dataclass-factory that already implement the serialization

lusty scroll
inland harbor
#

as is everyone

gleaming rover
inland harbor
#

You'll have to forgive my lack of familiarity with Python specifically, but here is my personal opinion there: I generally find composition much more expressive and less brittle than inheritance

inland harbor
#

what I mean by this is: rather than breaking your domain into a rigid hierarchy, where often you can only inherit from one ancestor directly, it's often more intuitive to define relationships in terms of what that particular class does.

In languages like Java, this is done using Interfaces

#

yeah

gleaming rover
#

because I believe that's what they were suggesting

#

there is no distinction between abstract classes and interfaces in Python

#

apart from actual usage

inland harbor
#

I would take a somewhat extreme stance on that, if Python abstract classes are similar to Java classes

#

Specifically, Java abstract classes allow you to share instance state with implementers

gleaming rover
#

or perhaps it is more accurate to say

#

there is no internal state except by convention

#

and because of dynamic typing, abstract classes are not really necessary, even

#

however, there is definite use of abstract classes to do what "interfaces" or "traits" would in other languages

inland harbor
#

My ideal system wrt interfaces is one which doesn't rely on any internal state whatsoever, and one which doesn't have the option of inheriting any state as in Java abstract classes

gleaming rover
#

but you can't enforce that in Python

inland harbor
#

no final keyword? too bad haha

gleaming rover
#

well

inland harbor
#

I apply that very liberally in my java code hehe

gleaming rover
#

you can kind of fake it with sufficient metaclass power

#

but it's not really part of the language's paradigm

inland harbor
#

I always flinch at the metaclass stuff haha...

gleaming rover
#

I kind of look @ it this way

#

either you go hard on the static typing

#

or hard on the dynamic typing

#

Python is the latter

inland harbor
#

yep

#

makes sense, I personally find it not so comfortable, and don't program much Python as a result hehe

gleaming rover
#

yeah, that's fair

inland harbor
#

I do a lot of Rust, which feels like a very static Python

gleaming rover
#

Rust is really nice

#

I like it a lot

#

in particular how they handle errors

inland harbor
#

mhm

#

still some pain points, particularly with async for me, but it's pretty nice

#

that may be a little simple for #internals-and-peps, but is there some standard Python way to print out thorough string representations of objects?
Not so much str(), but like an "everything and the kitchen sink"

#

possibly some kind of __blursed__ function which enumerates all the properties of a variable?

native flame
#

dir(x)?

gleaming rover
#

and, yes, dir(x) would be good

#

you might also want __dict__

inland harbor
#

dir? seems odd that would do what I'm looking for, but I could try.
Wouldn't be the first time something wasn't named what I expected

gleaming rover
#

this will, of course, not work for dynamic properties

inland harbor
#

I kinda figured hehe

gleaming rover
#

but I believe that would be equivalent to deciding function equality

#

someone with more theory can correct me

inland harbor
#

right, that makes 100% sense to me

raven ridge
#

it's possible to add dynamic properties to dir

#

by overriding __dir__ for your class

stuck valley
#

Yes. It's fun to mess with people who try and debug your code.

inland harbor
#

lol

#

wow, what does it mean when uvicorn is saying source code string cannot contain null bytes?

#

I don't remember adding any

lusty scroll
#

well, there's the pprint module

inland harbor
#

that's a good idea as well

lusty scroll
#

if you want to see everything though, you unfortunately have to write something yourself, probably using inspect.getmembers(object)

#

least, if there is something out there, I'd like to know what people use - help(object) is also handy

inland harbor
#

thought I'd ask if there was some kind of python library already which does this

acoustic crater
#

but for example dataclasses have great reprs

#

also to quickly access a __dict__ in a prettier way use vars()

#

also fun fact about repr you can get a repr in an f string with !r like f"{thing_to_repr!r}"

gleaming rover
stuck valley
#

I'm thinking about making a class which can't have instances made of itself.

dense rover
#

do you think i should install hackintosh

gleaming rover
#

why do you want to do that?

spice pecan
#

that wouldn't accomplish anything though

unkempt rock
#

what does this line of code do?

#
currentNode.right.remove(currentNode.value, currentNode)
#

is it equivalent to below?

self.remove(currentNode, currentNode.val)
#

or this?

currentNode.right = self.remove(currentNode, currentNode.val)
charred pilot
#

do you have the implementation

unkempt rock
#

yea

fallen slateBOT
#

Hey @unkempt rock!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

unkempt rock
#

it's 2000 lines long

charred pilot
#

your binary tree is 2000 lines long?

unkempt rock
#

my question isn't about binary trees

#

it's about how OOP aspects of the Python language work

flat gazelle
#

a.b.c() is equivalent to tmp = a.b; tmp.c(), so IG the former

unkempt rock
#

I see thanks

#

but how do I call a function/method like a.c() if it's inside a class

#

so I can only call it with self.c()

flat gazelle
#

you can call methods on any instances of a class, even outside the class itself

unkempt rock
#

I mean I'm trying to use a method inside another a method

#

like

class Classy:
  def __init__(self):
    self.val = val
class B:
  def hello(self, d -> Classy):
    myobj = d
    d.val.goodbye(g)  # except this doesnt work
  def goodbye(self, g):
    code
severe lichen
flat gazelle
#

attempting to model this with OOP would create a cyclical dependency, so it is not the way to go

flat gazelle
unkempt rock
#

yes, I'm trying to use a method in class B inside another method that is inside class B but I want to call it on an object created from a different class

flat gazelle
#

oh wait, I see.

#

yeah, that works

severe lichen
#

what about self.goodbye(d, g)?

flat gazelle
#

!e

class Classy:
  def __init__(self, val):
    self.val = val
class B:
  def hello(self, d: Classy):
    d.val.goodbye(10)
  def goodbye(self, g):
    print(self, g)
b = B()
classy = Classy(b)
c = B()
c.hello(classy)
fallen slateBOT
#

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

<__main__.B object at 0x7f45d995cfd0> 10
unkempt rock
severe lichen
#

Also, you can probably take the underlying function from a method and bind it to another object, and then call it...
But I wouldn't consider that a good idea.

What effect do you want to archieve?

flat gazelle
#

oh, you want to call a method with self not being an instance of its own class

#

that seems like a bad idea

unkempt rock
#

I'm not allowed to modify the original class

flat gazelle
#

well, the way to do that is

B.goodbye(d, 123)
#

if you access the function on the class itself, it will return the original function without binding it to an instance

unkempt rock
#

yea that's the same as doing self.goodbye(d, 10) I believe

#

which still doesnt work for resolving my error

#

thanks for the OOP info tho

unkempt rock
#

dumb question, what obje.att2.goodbye() actually do?

class Classy:
  def __init__(self, att):
    self.att = att
    self.att2 = None
  def hello(self):
    obje = self
    obje.att2.goodbye()
  def goodbye(self):
    obje = self
    return obje.att
#

I thought what it does is just call self.goodbye()

#

but I guess I'm wrong and it actually does self.goodbye(objce.att2) but it's not that either since when I run it doesnt work

#

nvm it does actually work when I changed the code to be

#
class Classy:
  def __init__(self, att):
    self.att = att
    self.att2 = None
  def hello(self):
    obje = self
    self.goodbye(obje.att)
  def goodbye(self, a):
    obje = a
    return obje.att
#

yea but when I instantiate the object, att2 is not None

#

obje.att2.goodbye() in that example seems to be self.goodbye(obje.att) (after changing the goodbye method a little)

#

sorry didnt mean instantiate, I meant after I change it

#

like

obj1 = Classy(10) # where 10 is att (self.att)
obj1.att2 = Classy(5)
#

I see

unkempt rock
#

I'm having issues on anaconda I'm trying to install netcdftime but It keeps saying failed with initial frozen solve and errors with pip too any fix

raven oar
#

What is the best gui module for Python?

paper echo
#

@raven oar this is on-topic for #user-interfaces, but there is rarely ever a "best" of anything in software

#

you are more likely to get a useful answer if you state your use case and needs

raven oar
#

I want to code multiple applications for not only windows

unkempt rock
#

ive got a question in machine learning

#

so the sigmoid function compresses the values of the sum into the range 0 to 1

#

but you can use other activation functions, such as ReLU or tanh, whos ranges are (0, inf), and (-1,1) respectively

#

how do you factor for this different range?

#

do you normalise for example in ReLU by dividing by the largest activation in each layer

#

and like (A+1)/2 for tanh, to bring it into the (0,1) range

#

just realised theres an ai chat putting it in ther

paper echo
#

@unkempt rock i see that you found #data-science-and-ml . but fyi this channel is for discussion of the python language itself

unkempt rock
#

yep, just got a bit confused

#

but yeh ill keep that in mind for next time

#

and ty for the help!

velvet phoenix
#

docker,kubernetes are considered as?

elder blade
velvet phoenix
#

idk these terms just seem to be popping more and more and they're kinda get me frustrated ahahhah

stuck valley
#

.c

#

c is pain to read

#

especially with that fun™️ wall of #includes

#

help()?

#

sys.modules?

sharp flume
#

i need this yesterday pls

sturdy timber
#

what would you use it for?

sharp flume
#

something terrible i made

mint sable
#

Can anyone help me code a advanced discord bot please

grave jolt
#

@mint sable This channel is for discussing the Python language itself. If you have a general question, ask in a help channel (see #❓|how-to-get-help) or in a specialized channel (like #discord-bots).

cobalt agate
# flat gazelle I would invert the control here. The GUI should ask the computation class for th...

Pursuant to yesterday's discussion,
I refactored the app here: https://github.com/zubin13/Ton_Miles_Calculator_Refactored
I have only used one class. When I tried to make the Computation class, I was having a lot of difficulty calling functions/instances from buttons and getting data into widgets -- all of which reside in the UI class. Perhaps my understanding of Classes is still very premature to do it successfully. However I have gotten rid of the global variables. And all the calculation functions are static in one file. It is slightly better than having a whole program full of static functions calling each other.

If anyone would like to take a quick glance through main_ui.py and give feedback on the class structure, and critical comments will be most appreciated.
@visual shadow @verbal escarp @halcyon trail @flat gazelle many thanks. My eyes are burning from two straight days of staring at the screen in vain, trying to work classes into impossible tkinter functionalities, but I will love criticism.
On the bright side, I came up with some very good UX improvements. This version toggles frames instead of destroying widgets and creating new ones. So user inputs are preserved.

GitHub

A Tkinter App to Calculate Ton-Miles Gained on the Drill Line on an Oil Rig - zubin13/Ton_Miles_Calculator_Refactored

verbal escarp
#

meep?

#

beyond me why you want to make this in tkinter 😉

#

but well..

flat gazelle
#

I mean, tkinter is pretty good for applications of this shape

verbal escarp
#

i'd say pyqt would've saved a lot of pain with those ui details

cobalt agate
flat gazelle
#
    drilling_miles_total = 0
    tripping_miles_total = 0
    casing_miles_total = 0
    liner_miles_total = 0
    jarring_miles_total = 0
    total_miles_result = 0
    formatted_date = 0
    comments = ''
```why not make these in `__init__`?
cobalt agate
cobalt agate
verbal escarp
#

flask is something else entirely

flat gazelle
verbal escarp
#

a web gui is not a bad idea, but different technology stack

cobalt agate
verbal escarp
cobalt agate
cobalt agate
verbal escarp
flat gazelle
#

self.a is shared per instance, all methods get the same self and thus the same self.a

cobalt agate
flat gazelle
#

unless you make multiple instances

verbal escarp
#

personally, i think tkinter is nice to have for very simple programs like installers etc.

#

wouldn't recommend it for anything more advanced

flat gazelle
#

I don't really think there is a better option, if you want to relicense to GPL, pyqt is an option, sure

cobalt agate
flat gazelle
#

alright, was just curious

#

but if if the ui is already written, why rewrite it?

verbal escarp
#

pyqt has weird dual/triple licenses

cobalt agate
verbal escarp
#

it's not just GPL

flat gazelle
#

ah, it is also under lgpl

#

which means that users will have install qt separately

cobalt agate
flat gazelle
#

it's just more verbose, but it doesn't really matter

#

it would matter if you were making more than one instance, but that doesn't make sense to do anyway

verbal escarp
flat gazelle
#

it's just mildly confusing

cobalt agate
flat gazelle
#

yeah, pyinstaller should work just fine for this

verbal escarp
#

yes

#

given it's the same OS

#

if you build it on windows 10 and want to deploy it on win 3.11, it might not 🙂

cobalt agate
flat gazelle
#

essentially, I don't think there is a meaningful reason to redo the entire user interface in a different framework considering that it already works in tkinter

cobalt agate
verbal escarp
#

uh..?

cobalt agate
verbal escarp
#

pyinstaller bundles pyqt etc. so users don't have to install anything extra

flat gazelle
#

as far as I can tell, that violates lgpl. You must keep the dependency under lgpl separate from the non gpl application so that it can be updated indepentently

cobalt agate
#

Correct. But as @flat gazelle pointed out, one of the others requires users to install qt searately?

verbal escarp
flat gazelle
#

qt itself is under lgpl, so they can't do a whole lot

verbal escarp
#

qt has different licenses

cobalt agate
#

Ok

verbal escarp
#

• Commercial license
• LGPL3 open source license
• GPL2 or GPLv3 open source license

cobalt agate
#

@flat gazelle this class implementation is better than the previous static functions? Does it provide any advantage you think or not much?

flat gazelle
#

unless you pay the several thousand dollars for the commerical license

flat gazelle
verbal escarp
#

i should warn you though, making pyinstaller work with pyqt isn't as straight forward as one might wish, although, once it works, it works.

cobalt agate
#

I've just built this to make my colleagues' and contemporaries' life easier as compared to using excel sheets. No such program exists anywhere.

verbal escarp
#

if you want to try that approach and you feel you hit a road block, you may poke me 🙂

cobalt agate
verbal escarp
#

tkinter is trivial compared

flat gazelle
#

I would suggest against lgpl deps unless you are on a *nix systems. Those were built to be run on mainframes, so they already support a single shared dynamically linked lgpl library that can be changed out for a modified version

#

doing this on windows is not quite simple

verbal escarp
#

You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:

a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.

cobalt agate
cobalt agate
flat gazelle
#

no, that's just for pyqt

#

tkinter is under the same license python is afaik

cobalt agate
#

While we're at it, what is your favorite method for storing passwords and keys as env when using an IDE? In a way that it can be easily transferred when you bundle the program as an exe or deploy it on the web? I've seen 4 different methods so far. The method whereby one enters the env by right clicking on the . Py file in pycharm obviously won't work once file is bundled and sent.

#

Another one I've seen is adding it to the bat files. And yet another one by creating env file

flat gazelle
#

I generally use a .env file

cobalt agate
flat gazelle
#

it is more or less impossible to store data on a users system and hide it from them with only your program being able to read it

cobalt agate
flat gazelle
halcyon trail
#

@cobalt agate the thing is you said "I didn't use globals" but then you have a bunch of class-level variables

#

class-level variables are just globals scoped to the class

#

As lakmatiol suggests, I'd probably just make them instance variables

cobalt agate
flat gazelle
halcyon trail
#

Yeah, it does

#

You kind of want to "postpone" admitting that anything is a global. You want to write everything as though it were normal classes, as much as possible, and then at the last second "gotcha!" there's only one global instance of class AppMain or whatever

paper echo
#

Namespacing is important

dry steeple
#

hey guys is anyone fimilar with telegram's api?

grave jolt
#

!pban 839670371896262686 spam

fallen slateBOT
#

:x: User is already permanently banned (#42761).

sand goblet
#

When does CPython check if a string is only ASCII letters and numbers and underscores and under 20 characters to decide to intern it? It doesn’t seem to do it for runtime strings because this prints False:py x = "my_test" y = "_string" a = x + y b = x + y print(a is b) # it prints False
And it seems like it interns all string literals whether they meet those qualifications or not because this prints True:```py
def f():
x = "my test- string ãbç over 20 characters"
return x

def g():
y = "my test- string ãbç over 20 characters"
return y

x = f()
y = g()
print(x is y) # it prints True```
When does it do those checks?

#
x = "my_test_string"
y = input()
print(x is y) # it prints False if you input my_test_string```
spark magnet
sand goblet
#

What’s the difference, is interning only when it does it during runtime?

spark magnet
#

compiled bytecode has constants in it.

sand goblet
#

Alright, that makes sense. But why are the strings separate objects in memory in the 1st and 3rd example?

spark magnet
#

(though they might be each in their own compiled bytecode function?)

sand goblet
peak spoke
#

getting the interned string for every string could be an unexpected runtime cost, you can try running it through sys.intern and seeing if that returns the same or a different string

sand goblet
#

!e ```py
import sys

x = "my_test"
y = "_string"
a = x + y
sys.intern(a)
b = x + y # same if it’s b = "my_test_string"
sys.intern(b)
print(a is b) # it still prints False```

fallen slateBOT
#

@sand goblet :white_check_mark: Your eval job has completed with return code 0.

False
sand goblet
#

I don’t get it

spark magnet
#

@sand goblet calling intern() wouldn't change a or b

peak spoke
#

You'd need to use the result from sys.intern, it'll return the interned string instead of the passed in string (if it was already interned)

sand goblet
#

!e ```py
import sys

x = "my_test"
y = "_string"
a = x + y
a = sys.intern(a)
b = x + y
b = sys.intern(b)
print(a is b) # it prints True now```

fallen slateBOT
#

@sand goblet :white_check_mark: Your eval job has completed with return code 0.

True
spark magnet
#

right, but that will work for any equal strings

sand goblet
#

!e ```py
import sys

x = "my_test"
y = "_string ãbç over twenty characters"
a = x + y
a = sys.intern(a)
b = x + y
b = sys.intern(b)
print(a is b) # it still prints True```

fallen slateBOT
#

@sand goblet :white_check_mark: Your eval job has completed with return code 0.

True
sand goblet
#

Yeah

peak spoke
#

afaik python will intern names (global names, and the keys for modules, classes etc.), there's not much reason to do it for others automatically.
I used intern once to avoid making my own dict when I wanted to prevent some unnecessary memory usage from many duplicate strings

sand goblet
#

But I guess that might technically not be interning

#

But that article seems like it’s saying that it is

#

I’m just trying to figure out when it does the ASCII check

#

I can’t figure out when it checks for that

spark magnet
#

@sand goblet keep in mind, this can change version to version also

sonic dagger
#
```py
# importing the library
import numpy as np
import matplotlib.pyplot as plt
import math

def diff(x,y,cx,cy,txt,list,dict):
    for i in range(len(x)):

        diffrence=math.sqrt((x[i]-cx)**2+(y[i]-cy)**2)

        dict[x[i],y[i]] = diffrence



# 2.23606797749979
#
# data to be plotted
y = np.array([-2,2,4,0])
x = np.array([-2,4,2,0])

k=[-2,1]
k1=[3,1]
print(k)

l1=[]
l2=[]
dictionary2={}
dictionary1={}
# plotting
plt.title("K Means")
plt.xlabel("X axis")

plt.ylabel("Y axis")
c1=plt.scatter(k[0],k[1], color="black")

c2=plt.scatter(k1[0],k1[1], color="black")
plt.scatter(x, y, color='b')

diff(x,y,k[0],k[1],txt="1 ",list=l1,dict=dictionary1)
diff(x,y,k1[0],k1[1],txt="2 ",list=l2,dict=dictionary2)

plt.show()
sand goblet
spark magnet
#

@sonic dagger don't paste a screenful of code in multiple channels

sonic dagger
peak spoke
fallen slateBOT
#

Objects/codeobject.c lines 64 to 72

if (all_name_chars(v)) {
    PyObject *w = v;
    PyUnicode_InternInPlace(&v);
    if (w != v) {
        PyTuple_SET_ITEM(tuple, i, v);
        if (modified) {
            *modified = 1;
        }
    }```
paper echo
#

What's a good use case for weakrefs?

prime estuary
#

The main usecase is caches, and things like that - you might want to store a cached computation for an object, but if the object is deleted you don't need that cached value - and you don't want the cache to keep it alive.

#

A WeakKeyDict can act like an attribute on an object, but it's external which is useful if it's implemented by another module.

#

They're also useful as a tool to prevent reference cycles, by making one direction weak.

halcyon trail
#

Python doesn't have separate notions of weak references and non-owning references, I suppose?

prime estuary
#

It does, via the weakref module.

#

You make a ref object, then can call that to retrieve a strong reference to the object.

halcyon trail
#

Okay, so that's a weak reference? Where's the non owning reference?

prime estuary
#

Well Python's GC knows about the weakrefs, and clears them if the object is destroyed. Is that what you mean?

halcyon trail
#

no, I mean that weak references as I'm used to thinking about them can be promoted to owning references

#

a purely non-owning reference would not

#

that's why I suspected that python does not make this distinction

prime estuary
#

Yeah, you can't do anything with the ref itself.

halcyon trail
#

that said in a GC language this idea of a purely non-owning reference probably makes no sense

#

the object you want to refer to could be destroyed at any moment potentially

#

so you need to upgrade your weak reference into a real reference first, which then ensures the object won't suddenly die on you in the middle of something

prime estuary
#

Yep.

spark magnet
#

it's not upgrading a weak reference, it's getting a new real reference

halcyon trail
#

sure

unkempt rock
#

How do I get awips cave installed on CentOS I tried it before but I keep getting errors

raven ridge
# halcyon trail a purely non-owning reference would not

they exist in the CPython implementation, but aren't exposed to Python. Code in the CPython C API has the notion of a "borrowed reference", which is an object that you hold a pointer to, but have not incremented the reference count of. They're mostly used for passing things down the stack - arguments are passed as borrowed references, because you know that the object can't be destroyed out from under you, because you know that the stack frame that calls you owns a reference to those arguments and can't drop it until after its call to your function returns.

#

they're also used for performance purposes in some places with the most fundamental types, like tuples. PyTuple_GetItem returns a PyObject* pointer to you for the item you've accessed without incrementing its reference count; it's the caller's responsibility to increment the reference count or forget the pointer before anything could happen that might destroy the tuple.

raven ridge
# paper echo What's a good use case for weakrefs?

In addition to using them to prevent reference cycles by making one direction weak, as TeamSpen210 said, the other place I've used them with some regularity is to perform cleanup. Sometimes you need to add a resource under some existing code, like adding a persistent TCP session underneath something that used to make a new TCP connection for each request it sent. Since you need to support accessing it without a context manager for backwards compatibility, you can register an atexit handler to destroy the session. Since you don't want the existence of that atexit handler to prolong the lifetime of the object if the user did explicitly close it, you can make the atexit handler hold a weak reference to the object, such that its job is to clean it up if it still exist when the app is exiting.

#

or something in that direction, anyway. "If object X still exists, do Y" comes in handy every once in a while.

dusty ledge
#

When is EAFP applied?

raven ridge
#

there are times when it needs to be used, because checking for an error condition in advance would result in a TOCTOU bug. If you want to remove a file if it exists, you can't check if it exists and then remove it if so, because something else could remove it in between you finding out that it does exist and you trying to remove it.

#

so the only safe way to handle "remove file X if it exists" is to try to remove the file, and handle the "it doesn't exist" error if removing it fails.

halcyon trail
#

@raven ridge thanks for all the info!

#

Your point about using purely non owning references for function arguments is very good

#

I was mostly curious because as a C++ dev of course non owning references are far more common than weak references, so I was just thinking a bit about it

sand goblet
#
def on_release(
        key,
        lock_for_dict_=lock_for_dict,
        held_or_released_=held_or_released,
        shown_keys_=shown_keys,
        hasattr_=hasattr,
        str_lower=str.lower
        ):```
Out of curiosity, does this make the function faster? Because I saw that it makes it have `LOAD_FAST` instructions instead of `LOAD_GLOBAL` instructions
raven ridge
#

Very slightly faster, yeah.

#

Looking up a local variable is cheaper than looking up a global variable.

sharp plover
#

You mean making a local reference to str.lower?

sand goblet
#

yeah through default arguments

#

What if you only use it a single time in the function, is it still faster?

sharp plover
#

Yeah, I believe it can be slightly faster. Although unless you need to change it, why make it a parameter? Edit: nvm I was confused 😄

sharp plover
sand goblet
#

I'm imagining it putting it in the array it uses for local values, so it ends up not needing to look it up in the global scope when you call it. Because it's already there.

raven ridge
#

Remember that default values are evaluated when the function is defined, not when it's called.

#

But the usual consensus is that you shouldn't do this. It's a micro optimization that, if code is important enough for, it's probably important enough to write in a C extension module instead

sand goblet
#

alright. It sounds like it's a goofy thing to do, thanks guys.

paper echo
#

I've gained significant speedups from doing it in functions with a long-running loop or that otherwise make repeated calls

#

Apparently global lookup can be significantly slower than local. Not sure how that compares to a single object attribute or dict lookup

#

(or weakref lookup as per above)

#

I remember a while ago someone posted an activestate script that resolved all global constants statically and then generated a new version of a function's source code with a bunch of these _local_foo = foo bindings at the top

#

Supposedly it was a big speed improvement on whatever their workload was

raven ridge
#

It's not that it doesn't improve the performance, so much as that if it makes a huge difference to your performance you're probably using the wrong language - or at least the wrong interpreter.

paper echo
dusty ledge
paper echo
raven ridge
#

True enough. I'm not saying "never", so much as "don't make a habit of it"

paper echo
#

A to-3.7 code generator could be useful, with polyfills/backports and some kind of "un-walrus" heuristics for common cases

#

That or ask your employer to donate to pypy

raven ridge
#

If you profile and find that some inner loop benefits from it, and you don't have time to move that inner loop to numpy or numba or Cython, then perhaps it's worth doing the hack

paper echo
#

Oh nvm these are 2 versions

dusty ledge
#

yeh idea 1 was the original which had so many checks

#

but if I try except it , it would have to check so much things anymore

paper echo
#

I would question the value of checking if something is a piece or not

#

That's what type annotations are for 😉

#
try:
    loc = board[new_y][new_x]
except IndexError:
    #if not inside the grid
    continue

try:
    loc_color = loc.color:
except AttributeError:
    #if obj not piece
    continue

if loc_color == piece.color:
    moves.append((new_x, new_y))
#

Could do it this way too

#

I really like keeping try/except checks as "small" as possible

vital nymph
#

guys can any1 help ??

paper echo
#

It makes it easier to see if you did it right

vital nymph
#

wdym ??

#

from pytube import YouTube
link = input("enter your link here : ")
yt = YouTube(link)
videos = yt.streams.all()
i = 1
for stream in videos:
print(str(i) + "-" + str(stream))
i += 1
stream_number = int(input("select a number :"))
video = videos[stream_number-1]
video.download()
print("download done :)")

paper echo
vital nymph
#

oh thanks

dusty ledge
paper echo
#

@dusty ledge But I think your "idea 2" is arguably better because it's more concise. However maybe you meant AttributeError instead of TypeError

dusty ledge
#

yep

#

ill change that now

paper echo
#

I would have multiple try/except if it wasn't very very obvious what the except's are catching

#

Overly broad excepts make for a really bad time debugging and testing

unkempt rock
#

If a and new_a are lists with them same length then these behave identically, right? py a[:] = new_a #VS for i in range(len(a)): a[i] = new_a[i]

#

Yep

#

Thanks rooYes

native flame
#

are they equivalent? I would assume in the first one it'd try to do a matrix multiplication and use the result as the decorator

unkempt rock
#

I was wrong pithink I could've sworn I noticed that behaviour the other day

fallen slateBOT
#

@unkempt rock :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     func: lambda = lambda x: x
003 |                  ^
004 | SyntaxError: invalid syntax
native flame
#

Callable

candid loom
#

can someone pls give me a basic python exersise

flat gazelle
#

just : Class

#

that implies the Class or any subclass thereof

native flame
#

just ast.AST then

flat gazelle
#

yeah, then it's just ast: ast.AST

lapis oar
#

hy

unkempt rock
#

Anyone know the best place to learn python

#

Online

astral osprey
#

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

unkempt rock
#

Thx

narrow timber
#

Hey guys! Excited to see so much going on in the Python Community. I am part of a project called Fortior Blockchain, which develops blockchain applications using Python! We recently released a paper focusing on smart contracts on the Algorand Blockchain, which has its own SDK for blockchain development. If you want to learn more, read our paper here: https://vixra.org/abs/2107.0097. That being said, I will be happy to answer any questions anyone may have about blockchain development in Python!

#

Oh gotcha! I was hoping to put educational material on here, and not neccesciarily advertise. I can edit the message.

paper echo
#

FWIW "use cases" of python is on topic

#

And i have to ask - why python? Wouldn't you want type safety guarantees, domain modeling with types, etc, in a blockchain application?

blissful comet
#

Looking for discussion on design by contract after PEP 316 from 2003. Here's a summary of my research on the topic and a proposal.

https://adsharma.github.io/pysmt/

narrow timber
blissful comet
blissful comet
halcyon trail
#

"other ML derivatives" sounds like its implying that python is an ML derivative

narrow timber
blissful comet
sleek mesa
#

Ohh

arctic ledge
#

does any one know how to convert h5 file generated to tflite Im trying to detect objects using maskrcnn tensorflow please help

iron canopy
#

Hey I’m new to python and I wanted to ask can someone help me code a discord bot which tracks u if u login to a Minecraft server like hypixel

elder blade
# iron canopy Hey I’m new to python and I wanted to ask can someone help me code a discord bot...

This might be a good question in #python-discussion, or the topical channel #discord-bots (where discord bots are made). You can also claim a help channel (see #❓|how-to-get-help).

You most likely want to use discord.py, check the pins in #discord-bots for a good guide. When you got your discord bot set up you want to look into how to use REST APIs, do some googling for that. Important note: Don't use requests with your Discord bot, it will block it and not allow other commands to happen while you are making that request

#

Hypixel should have an API for you to use, other Minecraft servers may not have that. Without an API there is no way of asking for the data you want.

iron canopy
#

oh k

unkempt rock
#

I installed miniconda but I keep getting traceback error no module name python38.dll

solid ermine
#

Is there a way for a base class to enforce that a subclass call 'super' for a specific method override?

spark magnet
solid ermine
#

I suppose I could write a decorator for it.

spark magnet
#

why not let the programmer do what they do?

#

every class needs subclassers to call super(), really

solid ermine
#

This is a case where the child class should union a set with the parent class... I think to get around it.. I might have the parent class just have a private set.. and then have a separate abstract method for the child class, then in the parent just union them

#

so. specifically, a set of attributes that are to be excluded from serialization

silver summit
#

where can I ask questions about the process of learning python?

solid ermine
#

parent class implements the method excluded_attrs

silver summit
#

ok thnaks

solid ermine
#

child class has a few attributes to exclude.. so it overrides the method excluded_attrs and should union it's list with the parent

#

parent's .serialize() will just call self.excluded_attrs() and it just works. I have issues when child classes don't union with the call to super and the parent attribute does not get excluded

flat gazelle
#

I believe some linter will warn about that

solid ermine
#

PyCharm is happy to let me not call super in that case :).. I feel like there's a pattern here I'm missing... I'll have to give it some thought

#

like aggregation

#

Composite..

flat gazelle
#

you could do something along the lines of

class Base:
    _exclude = {'b'}
    @property
    def exclude(self):
        res = set()
        for cls in type(self).mro():
            res |= getattr(cls, '_exclude', set())
        return res
class SomeChild(Base):
    _exclude = {'c'}
print(SomeChild().exclude)
```but it may be too much metaprogramming for something that could be far simpler
solid ermine
#

Honestly, that's very much what I think I need. That way I write it once, child implementations (which are many will be simplified.

flat gazelle
#

well, if you think this is the solution, go for it

solid ermine
#

It's along the lines of the solution I'm looking for, so definitely.. thanks

swift imp
halcyon trail
#

Couldn't you just have the serializer call the parent and child exclude itself

swift imp
#

The way I do it is like the parent has some ABC method _foo that the children must implement, and is used within foo method that the parent provides and the child inherits

halcyon trail
#

pretty much what lakmatiol wrote. He put it into another exclude function, I was just thinking of it being inline in the serialize function, but it's the same idea

#

that code iterates over the base and child and retrieves what to exclude itself

#

also btw what you're suggesting with foo and _foo is a well known pattern as well from other languages, or at least in C++, it's called the non-public virtual idiom

flat gazelle
#

yeah, there probably isn't much point in having that be a property, you can just inline to loop there

halcyon trail
#

non-public virtual interface idiom 🙂

flat gazelle
#

and I mean, that's what the _exclude is, a non-public virtual "interface"

#

or better, a non-public protocol, since this is python

halcyon trail
#

yeah, this is just fancier because it works for multiple levels of derived that each provide their own exclude

grave jolt
#

Any problem in CS can be solved with another layer of indirection (c)

halcyon trail
#

with "normal" NVI that's been discussed since ages ago in C++, you just call _exclude, which has to be provided by the derived class, you can't do anything like loop over the entire hierarchy calling each exclude separately

flat gazelle
#

that's what I do

#

loop over all the _excludes in the child class and all parents

halcyon trail
#

I know, I was just explaining the difference between this and NVI

flat gazelle
#

if you wanted distinct names for them, you would use __exclude, but I don't really like that

halcyon trail
#

exclude should also be a class method or even a static method, not that it really matters

flat gazelle
#

if you need it to have logic, sure

#

oh nvm I see

#

yeah, it could pretty easily be a classmethod as well

halcyon trail
#

sorry, yeah, classmethod, it cannot be a staticmethod

swift imp
#

Is there a book on these patterns but written in python

#

I tried to read gang of four but I don't know either of those languages well enough

spark magnet
#

be careful about trying to apply patterns from one language to another.

#

people treat the gang of four as a bible, but it doesn't all apply.

halcyon trail
#

yeah, I definitely agree with that

#

like half of that stuff is basically "shit, we can't pass around functions"

#

but half of it is still really relevant

swift imp
#

Someone said to me

halcyon trail
#

not always easy to know which half

swift imp
#

Patterns exist to make up for deficits in the language

#

But here we are talking about them in some abstract way

halcyon trail
#

yeah, this gets repeat a lot in the young, proggit/HN crowd, IME

#

I think this concept is basically a lisp invention

swift imp
#

Proggit/HNE?

halcyon trail
#

because lisp macros have pretty closed to unlimited power (within lisp), so the point is absolutely any repetition in concept (almost), can be written into a library using macros

#

instead of being an "idiom"

#

so the point is "if your language was more expressive, your idiom could be turned into a library, but it can't, so it stays an idiom"

#

I think it's worth knowing about this line of reasoning, but it's pretty overblown IMHO

spark magnet
#

i think it's a fair statement that patterns are how you put provided primitives together to do things they couldn't do already. in that sense, they make up for limitations of the language.

halcyon trail
#

In theory it sounds nice and there are definitely times where it's applicable but IMHO it's a bit ridiculous to make such a strong statement about it

#

sometimes the idea of a pattern could just be a trade-off between two different approaches. As an example that came up on this discord a while ago, and came up again in the cpp slack, the idea of parsing something and "pushing" vs "pulling"

#

"pushing" meaning that you pass the parser an object with callbacks and the parser calls the callbacks for you

#

"pulling" means that you ask for the next piece of data, which in python you'd typically write with yield, so typically i.e. a generator/iterator

#

In the C++ slack someone brought this up but under the names SAX vs StAX

#

and then of course a third option is just returning the data structure to the user, which this person called DOM

swift imp
#

As in Document Object Model?

#

Only seen that in xml/html

halcyon trail
#

so, I mean these 3 things are "design patterns" in some sense, they are very language independent, even though their manifestation could be pretty language dependent. But, you can't really factor this nicely into a library, IMHO, the whole point of the 3 approaches is likely to take advantage of specific relevant things in each case, which it's hard to imagine working well in any generic library (even w/ lisp macros)

spark magnet
#

@halcyon trail but as an example, all that debate over the parsing pattern is because these are not parsing languages. If we were working in yacc, there would be no patterns to discuss, because the language handles it natively.

halcyon trail
#

Well, yacc (as I understand it), isn't really a "parsing language" if you want to be technical about it. It doesn't do any parsing. You declare the grammar of the language you want to parse in it.

#

And then you have to compile yacc into your language of choice, and with your parsing strategy of choice

#

but if I'm misunderstanding please correct me, I haven't actually used yacc

spark magnet
#

it's between a language and a framework. You write a .y file, in its own grammar, so it's a language in that sense. The point is, it has the dynamics of parsing built in to it, so there's no need to discuss "patterns" of parsing.

#

It's a framework in that you write chunks of C code in your .y file, and they are invoked as the parsing progresses.

#

in a language with no function calls, there would be patterns of how to do something like function calls.

#

I think "patterns make up for deficiencies in languages" is strongly worded to get attention ("deficiency" is a loaded term), but I think it makes an accurate technical point.

halcyon trail
#

Maybe I'm misunderstanding but it sounds like yacc is basically using the push paradigm

#

it calls certain functions as certain things are processed

unkempt rock
#

Anyone know any good tv show/movie script generator

spark magnet
#

@halcyon trail yes, maybe it is, but my point is that when using yacc, you don't have to think about which paradigm to use, or construct one. you don't have to have a pattern, because the language has it covered.

halcyon trail
#

Well, the language has picked one for you. So here it's kind of the opposite; the design pattern doesn't exist because the language doesn't give you the option

spark magnet
#

right, you might not like the choice the language has made. but the point remains: if the language has already handled a need, then you don't need a pattern for it. Patterns are for things the language doesn't already do.

halcyon trail
#

I see what you're saying, although (maybe just my reading of it), it still tends to make it sound like a "bad thing" the language doesn't already do it for you

#

but yeah, I more or less agree

spark magnet
#

yes, the popular statement has been crafted to get attention 🙂

halcyon trail
#

that is very definitely true

static bluff
#
from typing import Any

class Command(dict):

  def __init__(self, **data: None | bool | int | float | str | Widget | Element):
    dict.__init__(self, **data)

    # commands are just packets of data, with a few extra behaviours attached
class Widget():
  # other stuff ...
  
  def dispatchCommand(self, command: 'Command'):
    ...
#

Is this type of circular dependence something I need to avoid?

peak spoke
#

is it just because of the typing?

static bluff
#

Yeah

peak spoke
#

No, just stick the imports under if TYPE_CHECKING with forward refs and you can ignore it

static bluff
#

And if it isn't something I should avoid — whats the difference between this and the type I should avoid?

elder blade
elder blade
peak spoke
static bluff
#

Though I do hear what you're saying

peak spoke
#

as long as it's typing, you'll be fine with what you had as long as the import is not executed at runtime

halcyon trail
#

It's usually better for classes not to have a cyclical relationship but sometimes it's the lesser evil

wraith herald
#

hi

#

i had a question

#

How many elements are in m = [[x, y] for x in range(0, 3) for y in range(0, 2)] ?

halcyon trail
#

6 I think

wraith herald
#

i see

halcyon trail
#

You could run the code and see?

wraith herald
#

i did but its showing a error

#

and i typed it out and its showing a error

#

and my sheet says that it should not show one

#

python is weird

halcyon trail
#

Can you show the error

wraith herald
#

Like screenshot is?

halcyon trail
#

Better to copy and paste the error probably

wraith herald
#

Okay bet

halcyon trail
#

Along with the exact code

static bluff
#

Well this really clears things up. Between this and cefpython3 for OSX upgrading to OSX and Linux this week, things are starting to come togther

#

XD Its been silent on the matter for months, and right when I needed it the guy who maintains it made a post saying it'll be out this week 😄 😄 😄

wraith herald
#

oh im such a idiot

#

I had a indent mistake

#

im so blind

halcyon trail
#

That said LexPlexed,.you may want to ask in a help channel, I don't think your question is really suitable for this channel

#

It happens to all of us :-)

wraith herald
#

Oh my bad haha

halcyon trail
#

Google rubber duck programming

#

No worried

#

Worries

wraith herald
#

👍

static bluff
#

I've got another one for you

#

Some helpful person on here explained to me that big composite classes are usually something to avoid. One class, one function. And its been a really helpful rule to live by

raven ridge
#

by "one function" you mean "one purpose" and not "one method", right?

static bluff
#

Anyway, my element class is meant to replicate most of the functionality of a Javascript element. To do this I usually spread this out over three base classes (to keep the element class from getting massive)

#

One responsible for writing the element out as markup (very much non-trivial); one to handle 'node' related stuff i.e. adding/removing/rearranging children and handling the parent-child relationship between elements; one to handle the dispatching of events

#

I want to know if this sort of arrangement is something you'd all avoid

raven ridge
#

hard to say without more details. I'd probably expect that to be two classes, rather than three - one handling "node" related stuff and events, one that knows how to take a node and serialize it as markup.

#

the first two seem to be fundamentally part of what it means for something to be a node (exists in a tree with parents and children, supports some types of events) and the other seems fundamentally different (given a node, do something with it)

static bluff
#

In javascript itself, node and eventTarget are separate — but I can do it however I like, really

#

I think in this case its fairly cut and dry but I wonder if you could offer some general wisdom on the topic of composing a class from multiple bases. When is it good, when bad, what are the pitfalls

halcyon trail
#

writing out an element as markup seems like it could be a function rather than a class; at least without more details; it's not really a stateful thing but just a transformation

raven ridge
#

I'm imagining it being a stateful visitor

halcyon trail
#

It could be implemented that way, but probably the stateful visitor could just be an implementation detail of a function, unless there's some reason to be able to inject different behavior during the visitation

#

hard to answer about pitfalls of composing a class from multiple bases without knowing why it's being done that way to start; the more common approach is to compose a class using, well, composition

static bluff
#

If I'm following along, you're discussing the merits of having the serialization be a method of the class itself. For reference, I've never had it alter the state of an element before so it'd just be an observer

halcyon trail
#

well, godly actually suggested it being a separate class

#

so, that's 3 different approaches I guess; separate class, separate free function, or member function

#

I prefer separate free function sall other things being equal because they're just the simplest. And as a general rule of thumb, things like serialization ought to be able to be done using the public API of a class

raven ridge
#

+1 on it needing to be implementable using the public API.

halcyon trail
#

If ti can be done using the public API that removes one of the strongest reasons for it to be a method and not a free function

raven ridge
#

things like indenting HTML output as you produce it are just easier with a stateful visitor than a stateless one, though - you can track the current indent level with an instance attribute, instead of needing to pass every detail down the call stack.

halcyon trail
#

Yeah, I agree withat, all I'm saying though is that speaks to implementation, rather than the public API

raven ridge
#

yep. I'm with you that it definitely shouldn't be part of the node class.

halcyon trail
#
class _StatefulVisitor:
    ...

def serialize(...):
    s = _StatefulVisitor()
    ...
#

something like that is what I would imagine

raven ridge
#

sure, that'd work.

halcyon trail
#

but it kinda depends what public API the node itself offers; whether it offers a callback (push) API or a generator/yield (pull) API

static bluff
#

Gotta admit, you two have kinda lost me

#

Though I thank you both for the help 🙂

#

And this if TYPE_CHECKING thing is a big relief. I'm still working really hard to avoid these kinds of relationships, but when push comes to shove its good to know theres an accepted solution

#

This idea of a visitor pattern is interesting. I won't pretend to know what you're talking about — but the notion of an external object traversing the hierarchy has interesting potential

#

I've got another one for you guys if its not too much trouble

#

This framework I'm working on, it replicates the DOM inside a python runtime and transmits changes to Javascript, I think I've probably got through this before so I hate to bore

#

Anyway, in the past I've rigged up a JSON encoder/decoder that would automatically encoding or decode elements passed as data in messages to/from javascript

#

Not too complicated — just have elements encode to {'__element__': True, 'id': element.elementID}

#

But to decode it, I need to have a registry of all instances of element, by ID. I'm wondering what the best way to implement this would be and, if this is a poor approach to begin with, what the alternative would be

static bluff
#

Well yeah, a dict 😛

#

But like, would it be best to store it globally inside the module that defines the base element class, or as a dict inside the base element class, or as a global registry somewhere else entirely like in the programs config file

#
class Element():
  
  INSTANCES = {}

  def __init__(self):
    self.INSTANCES[id(self)] = weakref.ref(self) # still not sure about using a weakref :|
#

I've got you guys' voices in my head as I work, always pushing me to do things the most pythonically. I want to get professional grade

halcyon trail
#

@static bluff btw, re our discussion long ago about a parsing API, and taking an approach where you yield back data vs a callback based approach. Something very similar to this came up in the cpp slack when we were discussing approaches to parsing, and someone was talking about DOM vs SAX vs StAX

#

There's not really my domain so I wasn't too familiar with the terms in that context, but it pretty much maps directly to the discussion

#

DOM -> return a data structure with all the parsed information, all at once
SAX -> A "push", event-callback driven approach
StAX -> A "pull", generator-iterator driven approach

#

if you're interested

static bluff
#

Thank you! 😮

halcyon trail
#

well, ok, StAX is a little more sophisticated than a generator, a StAX is a generalized, lazy approach, whereas generator is a fairly specific (albeit useful) lazy iterator

static bluff
#

I eventually ironed out most of the kinks in my lexer and I'm just letting it simmer for now

#

But I intend to have a compiler already waiting for when I get into compiler design in a few years 😄

cobalt agate
#

Do any of you use bootstrap along with Python/Flask? Would it offer a significant advantage if my html and css skills are very rudimentary?

#

Would using bootstrap be a shortcut to avoid going deep into html and css?

static bluff
#

That said, my preferred tool for web design is Webflow. Think photoshop but for web design. Awesome drag-and-drop interface that really takes the sting out of the front end stuff. Not 100% how exactly you'd set up the server on the back end but I'm certain its possible

crimson niche
#

People who are learning flask are typically concerned with the backend and not the front end, especially while learning.

#

You can definitely start with bootstrap.

crimson niche
#

Put it this way

#

You need to know enough html/css to implement bootstrap, but you don't need to be so good at CSS that you can design something as sophisticated as bootstrap.

cobalt agate
static bluff
#

As to whether or not it'll be enough for decent-sized project, if I'm being honest, the answer is probably not. I've been programming for years and I'm only just starting to put out 'professional-grade' software, though I didn't get a formal education so that slowed things down

#

But thats no reason not to do it anyway. Trial by fire, baby! Once you sit down and start doing it you'll start figuring out pretty quick what you need to know, and then you'll learn it 😄

static bluff
#

Its amazing to watch a program transform over time, eh?

sand python
#

!e why is this the behavior for formatting bools? ```py
print(format(True,''))
print(format(True,'5'))

fallen slateBOT
#

@sand python :white_check_mark: Your eval job has completed with return code 0.

001 | True
002 |     1
flat gazelle
#

Bool is a subclass of int, and it doesn't override format, but format '' delegates to str

lament sinew
#

these are equivalent to '{}'.format(True) and '{:5}'.format(True).

sand python
#

so an empty format string would call bool's str, and a nonempty one would call int's __format__. hmm

#

surprising behavior, is there any reason to not add an override for bool's __format__?

flat gazelle
#

My guess is it slipped under the radar

acoustic crater
#

!e format

fallen slateBOT
#

@acoustic crater :warning: Your eval job has completed with return code 0.

[No output]
acoustic crater
#

wtf format is a global function

#

never parsed that before somehow

#

other built in constants don't format their own name when given '5' as a format spec

#

why should True and False? that behavior isn't supported for constants, so use the superclass's behavior

flat gazelle
#

Yup, it calls the format of int, which will pad it up to a length

small roost
#

is there any difference between .format and a formatted string (f" ")?

prime estuary
#

They have slight differences - str.format has its own syntax for indexing/getting attributes of the value first, while f-strings can just use regular code.

#

And str.format can be applied to strings you construct at runtime, since it's not a literal.

small roost
#

Alright thank you

#

makes sense now

prime estuary
#

But they both delegate to __format__ in the same way.

unkempt rock
#

!e format

fallen slateBOT
#

@unkempt rock :warning: Your eval job has completed with return code 0.

[No output]
cobalt agate
#

Pycharm is really making me tear my head out. Not loading my changes to index.html in Flask no matter what I try. Can someone help in #help-pear ? I've tried saving, reloading, restarting debugger every possible solution on stackoverflow.

magic python
#

is it considered bad practice to have multiple logging.basicConfig ? If i setup logging for each module, what am I missing?

halcyon trail
#

Doesnt logging.basicConfig only configure the root logger

#

This function does nothing if the root logger already has handlers configured, unless the keyword argument force is set to True.

#

I would say yes, it's pretty bad form

#

That function is usually only called in main

magic python
# halcyon trail That function is usually only called in main

only called in main of what, the module where there's if __name__ == '__main__' ? (not sure if main is overloaded).

I've no idea what logging.basicConfig configures really 🤔

looking through some projects it seems as though they don't use it at all

#

and just do logger = logging.getLogger(__name__) then use from there

#

maybe i'll just not config it 😅

halcyon trail
#

You don't have to use it

magic python
#

yeah i can config it so that the printing output is nicer, but maybe that's missing the point of logging a bit

halcyon trail
#

It's just a very convenient way to quickly configure the root logger which is what most simple python programs want

#

Well, it lets you set the filename, level, format, and a few other things at once

magic python
#

yeh i'm in a monorepo here so basically everything is in it, rather than a single package

halcyon trail
#

Most of my scripts, I have something like if name == main: main()

#

In main() I parse arguments first

#

The log file and log level is often based on the command line arguments

#

So after doing the argparse stuff I call basicConfig

#

You don't have to use basic config but with rare exceptions it's mostly the end user who should be configuring loggers

magic python
#

kind of the end user and the developer here so it gets blurred sometimes

halcyon trail
#

Most packages should just be doing logger = logging.getLogger(name) and then logger.info or whatever

#

Well the idea still applies to the code

magic python
#

right - i think i might stick with that then for now, then when something is settled change basicConfig somewhere that actually makes sense to use it

halcyon trail
#

At any rate for 95 percent of my code the only config I do is basicConfig in main

#

Sometimes I've attached handlers to write to a specific file deeper in the code

magic python
#

yeah i remember doing something where it inherited from a logger defined elsewhere, it was ages ago tho and i probably did it wrong then.

Feels like no basicConfig is the safer option for now at least 🙂

halcyon trail
#

It's not less safe just more convenient

#

Instead you'll just go through the multiple calls to set level, create and add a handler, etc

magic python
magic python
elder blade
magic python
elder blade
#

You can checkout this server's repositories, they do exactly this (I know for a fact that Pixels does at least).

You can also take a look at libraries like discord.py, you should see that line at the top of almost every file.

magic python
dusty ledge
#

When should I use isinstance vs type yert

elder blade
#

isinstance matches subclasses

spark sail
#

Gi

#

Hi

halcyon trail
#

@magic python in a module/package, yes, that's all you should be doing

#

that code, and basicConfig serve two totally different purposes. That code is to actually do the logging, basicConfig is to determine what actually gets visibly logged, what it looks like, and where it goes (stderr, a file, etc)

#

The alternative to basicConfig isn't that code, it's more like

logging.getLogger().setLevel(logging.INFO)
logging.getLogger().addHandler(logging.Handler(logging.FileHandler(...), format=....))
#

code like this, or like basicConfig usually only appears at the "top" of the application, i.e. in main or near it, because that's the point in the code that's best qualified to make these decisions. The whole point of logging design is that the packages can just log without thinking about any of these things, and yet the whole system is flexible enough to give top of the application detailed control over what gets logged

magic python
delicate ice
#

Hello guys is there is way i can make live user input i m using rich library so that it update when i enter the password

sacred yew
dusty ledge
#

Is the logic here good?

len_ = 0
for x in somelist:
  if len_ == 10:
    break / return False
  if instance(x, class):
    do smth
  len_ += 1```
#

Specifically len_ part

#

So I won't have to do 2 loops?
1 for len And 1 for checking each?

prime estuary