#internals-and-peps

1 messages · Page 59 of 1

sullen citrus
#

so if i'm not stupid sorted() changes the value temporarily and we can assign it to a variable, and sort() changes the value permanently ?

spice pecan
#

sorted creates and returns a sorted copy

#

list.sort just runs on the original list and modifies it

sullen citrus
#

yup thanks

#

i don't know but i forgot it...

#

take care!

eternal ocean
#

so```
0 = {}
succ n = n U {n}

@grave jolt in Haskell, succ n will return n+1

grave jolt
#

not necessarily

#

succ is a member function for the Enum class

#

but why does it matter here? it's just a mathematical successor function

deft pagoda
#

can use surreal numbers for ints:

In [3]: zero = Number() 
   ...: one = Number(L=(zero,)) 
   ...: two = Number(L=(one,)) 
   ...: minus_one = Number(R=(zero,)) 
   ...: two + minus_one == one                                                                                          
Out[3]: True
boreal umbra
#

Do you always use notebook-like IO instead of repl IO for your code samples?

#

(Not saying that one is better than the other; just wondering)

languid nimbus
#

hi, so i modified the default json module: https://paste.pythondiscord.com/jecoranuyi.py, and was wondering if i should submit it as a pull request, the changes are as follows 92: import copy.copy for later use 105-148: add functions _do_replace and _sanitize 152: add sanitize kwarg (default False) 180-181: add sanitize to docstring 187-188: add sanitize functionality 211: add sanitize kwarg (default False) 238-239: add sanitize to docstring 245-246: add sanitize functionality i've tested it and it works as intended currently, its function is to allow non-serializable objects within the obj argument of json.dump and json.dumps to be cast to a string in order to make the entire object serializable

spiral willow
#

Zoe, if you want, touching system libraries is always fraught with "we can't break anything" so make sure run whatever test python has json module with 100% pass and whatever changes you made include tests as well

languid nimbus
#

i mean, it wont break existing code, because of the fact it only does anything different when a non-default Kwarg is used, but i mean, im not 100% sure that the new code is completely bug free, but i havent been able to find any bugs

spiral willow
#

I've never contributed to python core libraries but I assume they have test modules

languid nimbus
#

it seems like they do, i'll use them if they exist

spiral willow
#

I'd be shocked if they didn't

peak spoke
#

I'd probably start with posting it on something like python's mailing lists or creating an issue for it

#

The general usefulness of the feature needs to be considered, as adding it to the stdlib also means maintaining it for quite some time

languid nimbus
#

okay, thats fair

paper echo
#

!e ```python
def run_once(fn):
ran = False
def wrapper(*args, **kwargs):
nonlocal ran
if ran:
result = fn(*args, **kwargs)
ran = True
return result
else:
raise RuntimeError('Stop that')
return wrapper

@run_once
def f(x):
print(f'{x=}')

f(3)
f(3)

fallen slateBOT
#

@paper echo :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 17, in <module>
003 |   File "<string>", line 10, in wrapper
004 | RuntimeError: Stop that
paper echo
#

@unkempt rock @sand goblet @pearl river ^ re: "run this function only once"

#

not sure why it isnt printing, i probably goofed something up

#

oh

languid nimbus
#

thats quite a nice idea actually

paper echo
#

!e ```python
def run_once(fn):
ran = False
def wrapper(*args, **kwargs):
nonlocal ran
if ran:
raise RuntimeError('Stop that')
result = fn(*args, **kwargs)
ran = True
return result
return wrapper

@run_once
def f(x):
print(f'{x=}')

f(3)
f(3)

fallen slateBOT
#

@paper echo :x: Your eval job has completed with return code 1.

001 | x=3
002 | Traceback (most recent call last):
003 |   File "<string>", line 17, in <module>
004 |   File "<string>", line 6, in wrapper
005 | RuntimeError: Stop that
paper echo
#

there we go

#

yeah @languid nimbus i hate it less than i thought i would

languid nimbus
#

ahaha, fair enough

paper echo
#

i also much prefer this to one suggested method of overwriting fn.__code__ with (lambda: None).__code__......

#

or this creative but bizarre solution by mesolikey:

def f(x=[0]):
    print("function called")
    x[0] = 1

for i in range(3):
    if f.__defaults__[0][0] == 0:
        f()
pearl river
#

once you start using mutable defaults, you don't stop 😅

paper echo
#

this is truly the first time i have ever seen mutable defaults used as a feature rather than an unfortunate side effect of language design

#

i wonder if you can implement some kind of recursion with mutable defaults

#

oh god you can

languid nimbus
#
def self_destructing_function(x):
  print(f'{x=}')
  del globals()['self_destructing_function']
``` because i like to watch the world burn
pearl river
#

You can use them for caching 😉

languid nimbus
#

@paper echo what about my little gem 😈 😂 😂

unkempt rock
#

@paper echo The above code is giving me the Stop that RunrtimeError

#

thats the whole purpose?

languid nimbus
#

thats what happens when you run it more than once, to my understanding the objective was to create a function which can only be called one time

paper echo
#

yes

#

lol zoe

languid nimbus
#

is it creative enough 😂

deft pagoda
#

that's what i've used mutable defaults for --- caching

paper echo
#

brutally so @languid nimbus

fallen slateBOT
#

:incoming_envelope: :ok_hand: applied mute to @unkempt rock until 2020-07-24 03:13 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

last pollen
#

cool

modern gale
#

Uh

unkempt rock
#

is it okay if i use python 3.8 when the python 3 book tells me to download 3.6. i dont think 3.8 came out when the book did.

#

?

near coral
#

yes

#

not a huge difference between the two

deft pagoda
#
In [3]: def self_destruct(func): 
   ...:     def wrapper(*args, **kwargs): 
   ...:         result = func(*args, **kwargs) 
   ...:         del globals()[func.__name__] 
   ...:         return result 
   ...:     return wrapper 

there's a decorator for it

unkempt rock
#

alright thanks jason. i got the right book this time 😄

languid nimbus
#

nice, ahaha

#

in the interest of avoiding typos ```py
import inspect

def self_destruct(x):
print(f'{x=}')
del globals()[inspect.stack()[0].function]

surreal musk
#

um

near coral
#

what is the inspect library?

surreal musk
#

ok this is advanced

near coral
#

I haven't used globals() before either...I am learning

languid nimbus
#

inspect allows you to inspect live objects, it has a bunch of useful features inspect.stack()[1].function is the name of the function which called the current function, which could for example be used to only do a certain thing if a function wasn't called directly.

#

okay, yeah... don't use globals() unless you have a very specific reason to, its really not good practice ahaha

deft pagoda
#

i've used locals to create a bunch of kwargs before

near coral
#

global variables?

deft pagoda
#
    def keyboard_on_key_down(self, window, keycode, text, modifiers):
        """Emulate a python console: disallow editing of previous console output."""
        if keycode[0] in CTRL or keycode[0] in SHIFT and 'ctrl' in modifiers: return

        key = Key(keycode[0], 'shift' in modifiers, 'ctrl' in modifiers)

        # force `selection_from` <= `selection_to` (mouse selections can reverse the order):
        _from, _to    = sorted((self.selection_from, self.selection_to))
        has_selection = bool(self.selection_text)
        i, home, end  = self.cursor_index(), self._home_pos, len(self.text)

        read_only = i < home or has_selection and _from < home
        at_home   = i == home
        at_end    = i == end

        kwargs = locals(); del kwargs['self']
        if handle := self.input_handler(key, read_only): return handle(**kwargs)

        return super().keyboard_on_key_down(window, keycode, text, modifiers)

this was where i used it

languid nimbus
#

yeah, globals() is basically a dictionary of all of the global variables in your code

near coral
#

got it

#

do you have to specifically declare a variable as global?

#

I have never done that

languid nimbus
#

unless its in the uppermost scope, yes

#

and i would advise against doing so

deft pagoda
#

only if you need to modify it

#

and it isn't a mutable

languid nimbus
#

ye

#

that too, but at that point, use a class

near coral
#

I don't see any need for global variables, so I can see why they advise against it

deft pagoda
#

for meta programming and making frameworks you might use globals

languid nimbus
#

it can be useful in certain very specific situations, like for example i had a piece of code that imported modules based on a dictionary, and it had to use globals() to assign names to the imported modules

deft pagoda
#

i use it for hot-reloading in ipython

near coral
#

I have never made frameworks

#

this is advanced stuff 😁

#

I can see how inspect could be useful, especially for debugging

#

I usually use breakpoints and then evaluate expression in pycharm

#

it will list all members of an object for me

#

it is a bunch of metadata

languid nimbus
#
import importlib

imports = {
  'kivy' : {
     'uix' : ['Label', 'Button', 'FloatLayout']
  }
}
for k, v in imports.items():
   for l, b in v.items():
      for i in b:
        globals()[i] = getattr(importlib.import_module(f'{k}.{l}.{i.lower()}'), i)
``` this is the import snippet i was using, this way i can easily add kivy imports, because otherwise, they're quite awkward to type out
#

thats just one v specific example where there's basically no alternative to using globals

near coral
#

oh I see

deft pagoda
#

oh i had a kivy meta hack to auto import properties and auto load kv files

#
from collections import ChainMap
from inspect import getfile
from os.path import dirname, join, exists
from textwrap import dedent

all_properties = {name: getattr(properties, name) for name in properties.__all__}

class WidgetMetaclass(type):
    def __prepare__(*args):
        # "Add" Properties to __dict__
        return ChainMap({}, all_properties)

    def __new__(metas, name, bases, methods):
        # Remove Properties from __dict__
        if hasattr(methods, 'maps'):
            methods = methods.maps[0]
        return super(WidgetMetaclass, metas).__new__(metas, name, bases, methods)

    def __init__(cls, name, bases, attrs):
        super(WidgetMetaclass, cls).__init__(name, bases, attrs)
        Factory.register(name, cls=cls)

        kv = getattr(cls, '__KV__', None)

        if not kv:
            directory = dirname(getfile(cls))
            filename = f'{name.lower()}.kv'
            kv_path = join(directory, filename)

            if exists(kv_path):
                with open(kv_path, 'r') as file:
                    kv = file.read()

        if kv:
            Builder.load_string(dedent(kv))


class WidgetBase(EventDispatcher, metaclass=WidgetMetaclass):
    '''Base class used for Widget, that inherits from :class:`EventDispatcher`
languid nimbus
#

thats pretty cool actually

dire hull
#

could someone maybe explain where did i go wrong with this

#

is it because i wasnt using C syntax/logic to concatenate?

#

i only know C++ but C docs suggests copying starting from NULL then create new string then adds NULL to new string idk

dire hull
#

found the problem in case anyone wondershttp://docs.cython.org/en/latest/src/tutorial/strings.html#general-notes-about-c-strings

tawdry gulch
#

Wait how does that work

#

I assume there is a realloc call backstage there

brave badger
#

You could try analyzing the outputted C code

dire hull
#

jupyter doesnt seem to gib that guess i gotta switch ide then lol

#

since this problem persists after switching from C string to python string object i m guessing theres some shenanigans happening lol

brave badger
#

@dire hull Save the snippet to a .pyx file and run cython -a *.pyx on it, my guess is that Cython is treating string as a Python string and is reallocating it multiple times

#

Also I think this is a bit off-topic for this channel, maybe we could move to ot

dire hull
#

oh yes sry

#

ot2 then

languid nimbus
#

@deft pagoda i made it more powerful ```py
def self_destruct(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)

    try:
        del globals()[func.__name__]
    except:
        pass
		
    try:
        delattr(__builtins__, func.__name__)
    except:
        pass

    return result
return wrapper

print = self_destruct(print)

print('!')
print('!')

ancient moat
#

which language was python made from?

last pollen
#

what do you mean by made from?

ancient moat
#

like I mean, python the language must have been coded right?

last pollen
#

The official implementation of Python is CPython, written in C

ancient moat
#

oh ok thanks

coral flame
#

can someone explain this

#

Also the search engines dont seem to understand the expression \\

flat gazelle
#

\ starts an escape expression in python. For example \n is newline, \\ is \, \r is carriage return, ... You can use r'\\\\' to get 4 backslashes in a row

#

r prevents the escape sequences

coral flame
#

aight thanks m8

flat gazelle
#

the character is called backslash

pearl prairie
#

hello

slim island
#

Hello @pearl prairie - this isn't the best channel for introductions. IF you just want to chat and introduce yourself, #python-discussion is bit better if it's about python in a general sense - or off-topic if it's more general.

magic python
#

@brave badger cython seems like an interesting part of the language, so on topic? 🤔

flat gazelle
brave badger
#

Yeah, also considering that Cython is a superset of Python

thorny epoch
#

Python is best

unkempt rock
#

Hey, I'm making a discord bot with python and I am working on a new command where I get some user account data

#

There's an open source javascript/node bot that does almost the same thing

#

This is a small part of that code, my question is: How can I do something like this with python/aiohttp?

brazen jacinth
unkempt rock
#

Oh alright

dusk yacht
#

How do you import stuff from a directory one level above it? I tried import ..utils but no. I'm asking here because I think a help channel is overkill for this

brazen jacinth
#

from .. import module if they're both a package afaik

paper echo
#

@dusk yacht that's correct but only if it's a package, not a just directory. And yes a help channel is fine for this. We have a lot of help channels for a reason.

gusty breach
#

Hi, I generate an object in a loop and when I insert the object with the iteration, I get something like this:

{
    "2500": {
        "animal": {
            "fish": {
                "blobfish": {
                    "age": 3,
                    "location": "sea",
                    "status": "alive"
                }
            }
        }
    },
    "2501": {
        "animal": {
            "fish": {
                "clownflish": {
                    "age": 1,
                    "location": "aquarium",
                    "status": "dead"
                }
            }
        }
    }
}

Got any clever idea how I could change it in a way that I save both entries under the same child?

brazen jacinth
quasi shuttle
#

hey guys when asking a user for input to remove an item from a list, how do i make sure that the input given matches an item in the list. for example if i have 3 items in a list, how to stop someone trying to delete the 4th item that don't exist?

brazen jacinth
quasi shuttle
#

ok thank yuo

proud quarry
#

Hey is it possible to specify types in python, i tried this but probaly not valid: test: str = 'asd' it does work tho

peak spoke
#

Those are type hints, https://www.python.org/dev/peps/pep-0484/ they aren't used directly by python but are added to the __annotations__ variable when sued in functions etc. Type checkers
like mypy can then use them to help verify you're passing the right things in your code

proud quarry
#

Ah okay thanks

sullen citrus
#

Hi, please can someone explain to me what does the items() function does exactly on the dictionary ?

paper echo
sullen citrus
#

ah ok... thx

#

take care

severe axle
#
print('you all good')
spark parcel
#

With new updates to the python language, like 3.9, is the branch for it public or do they release it more in an Apple manner?

#

I suppose it’s public, but I’m not quite sure

severe axle
#

yeaaa

brazen jacinth
#

apple manner?

severe axle
#

Hmmmmm

#

no

brazen jacinth
#

they do follow a release cycle

severe axle
#

yea

#

but

spark parcel
#

Apple manner means that everything is secret, until release date

#

Almost everything regarding python is open, right?

brazen jacinth
#

yea, python does not follow in apple's footprints

peak spoke
#

The code is all on github, but I believe you'll have to find an unofficial build or compile it yourself

brazen jacinth
#

everything is public, or at least open to the eyes of the public

#

open source vs proprietery etc

spark parcel
#

Hmm, okay

#

So, we basically know what to expect of 3.9 already?

brazen jacinth
#

yep, peps are public, feature planing is public, implementation issues are public

spark parcel
#

Nice. Is 3.9 just a separate branched that’ll be merged with the master soon, then?

brazen jacinth
#

im not sure of the specifics, but something like that most likely

#

im sure the precise branching flows are described in detail in some part of the developer docs

spark parcel
#

That’s true

#

I’ll take a look. Thanks

spark magnet
#

@spark parcel there are official builds of 3.9.0b5 available

spark parcel
#

Really? Thanks for letting me know

paper echo
#

this is gonna be a good one

#

zoneinfo is really really useful

#

as is graphlib

#

pep 617 (new parser), pep 584 (dict merge operators), pep 585 (type hinting w/ generics), pep 614 (decorators can be full expressions now)

#

asyncio.to_thread (presumably this one was borrowed from trio)

#

has there been a pep for something akin to perl's use statement?

#

obviously you can specify in setup.py/pyproject.toml

peak spoke
#

3.9 has a lot of cool stuff but I'm more looking forward to 3.10 and the breaking changes it'll introduce

swift imp
#

Like?

paper echo
undone hare
#

PEP585 is such a small change but it is soooo good

paper echo
#

i need to read pep 585 in detail

#

im really interested in static typing in general

peak spoke
#

Postponed annotations as one example malendowski, then if peps go through also things like removing deprecated modules etc.

paper echo
#

Starting with Python 3.7, when from __future__ import annotations is used, function and variable annotations can parameterize standard collections directly. Example:
i actually had no idea about this

#

where's the list of changes so far, if not in the docs @peak spoke ?

#

oh i see mypy didn't handle it before now

swift imp
#

Wait so are the new static types going to make runtime checking easier?

#

Bc currently with Typing module , it sucks and doesn't really work

#

I know mypy exists but I'd rather runtime checking if so desired

undone hare
#

The zip() function now has an optional strict flag, used to require that all the iterables have an equal length
Isn't that the current implementation, raising if they don't have the same length, while zip_longuest doesn't give a f*ck about the length lemon_thinking

peak spoke
#

Most peps that had python 4 as the version where they switch over to default are now on 3.10, the some more cool things like subinterpreters if they finish, the what's new doesn't have that much since it's an alpha

#

zip will just stop on the shortest

halcyon forum
#

can someone tell me how i can understand why i am getting this error with pip install:

Collecting python-harvest-2
  Could not find a version that satisfies the requirement python-harvest-2 (from versions: )
No matching distribution found for python-harvest-2
pearl river
#

I kinda like generics being uppercase capitalized, but not having to import from typing is enough of a reward.

paper echo
#

it's the same as before @swift imp it just removes the need to use typing.List[T], now you can write list[T]

peak spoke
#

The only change 585 brings is moving over behaviour of things like List to the builtins and deprecating the imports

swift imp
#

Yeah but you can't use isinstance on anything in the typing module, you should be able to in 3.10 right?

#

Like if you pulled the annotations with inspect

paper echo
#

pep 585 says that isinstance will still give an error on parameterized types

#
isinstance(a, list)       # OK
isinstance(a, list[int])  # ERROR
swift imp
#

I'm guessing they're still working it out and will allow it eventually?

#

I want that so bad

paper echo
#

i doubt it

#

its fundamentally not possible at runtime in many cases

undone hare
#

isinstance(a, List) is a thing though

paper echo
#

or not feasible

undone hare
#

Maybe they could do that with a dunder, but I also doubt it

paper echo
#

you can't tell if a list is a list[int] at runtime unless you literally check every element

#

and what if it's an Iterable?

#

then you've exhausted it

#

RIP

swift imp
#

If you wanted to allow iterables then you annotate as Iterable instead of list

paper echo
#

that's not my point

brazen jacinth
#

it's not built into the language, everything will be a workaround

peak spoke
#

I like the way typing is handled since python is so dynamic but tools are still allowed to handle the annotations in their own way

brazen jacinth
#

use a static language if you want static typing 🤷‍♂️

undone hare
#

They are some funny itertools iterables to check the content of an iterator without exhausting it though

swift imp
#

Exactly @undone hare

paper echo
#

@brazen jacinth or statically typed collections like numpy.ndarrays or array.arrays

peak spoke
#

I'm assuming that'll be more expensive than you want a type check to be

paper echo
#

@undone hare oh?

brazen jacinth
#

Or that yea

swift imp
#

Having to write code for end users who don't want to read documentation and shit, static typing would be really nice

peak spoke
#

and if it's with things like tee then they're also not threadsafe

undone hare
#

Maybe not itertools, but I remember seeing that in the standard library; it isn't complicated to write anyway, just break the idea of the iterator

slim island
#

I sometimes wish I could easily turn out static typing for Python - static languages are very nice when they just run the first time. It takes much more effort to get it right first time in Python, but any improvements in the typing ecosystem is a good thing

swift imp
#

Like my office is so fucking bad, there like 4 people that actually can and like coding. The rest just want some box that spits out answers

undone hare
#

F for compile time if type checking is a thing though

paper echo
#

@swift imp use marshmallow for input validation imo

#

and attrs with slots=True

brazen jacinth
#

or just build a simple flask app if you're not dealing directly with coders?

rich steppe
#

what the use ->, : in ``def greeting(name: str) -> str:
return "name is {}".format(name)

print(greeting(100))`` if we input and return different types

peak spoke
#

Tools can warn you

paper echo
#

yep

#

pycharm does this for example

#

if i write -> int there it will warn me that i got the type wrong

#

and more importantly now i can write

g = greeting('salt rock')

and pycharm knows that g is a str

slim island
#

Typing has made me hate any packages that don't type hint

paper echo
#

^^^^^

rich steppe
#

thanks

slim island
#

AWS is the biggest and most annoying example, none of their stuff is type hinted

red solar
#

because it's generated at runtime

#

who tf's idea was that

rich steppe
#

is it important

#

should I also start doing it

paper echo
#

boto docs are also just bad

peak spoke
#

I've been having a lot of trouble with bs4 recently with the system it uses and having no idea whether I only get tags or also things like strings

red solar
#

it's a massive quality of life improvement for the user of said library if you have type hinting

peak spoke
#

Hints would be great there

paper echo
#

@rich steppe i think it will be both educational and it will make your own life easier in the long run

slim island
#

@peak spoke that's one that I was trying to think of that caused me a lot of pain recently

paper echo
#

i'd love a tutorial or doc on "how to add type hints to a library that doesn't have them, using .pyi files"

#

that's such an easy fix

#

but i think people just don't know how to write type stub files

red solar
#

.pyi?

#

what's this?

peak spoke
#

I tried writing a hint for a method in bs4 but ended up discovering they have some recursive checks there

undone hare
#

Stub files, they are here for annotations

red solar
#

oh is this a mypy thing?

undone hare
#

(i is for interface)

#

Yup

brazen jacinth
#

i like type hints, but when the complexity of a program grows, i just can't be arsed to lookup what i need to make it rigirously typed

#

triple nested structures, etc etc

slim island
#

If you just type things from the beginning, it's pretty easy

paper echo
#

on the flipside, i can't be arsed to write complex code without typing

red solar
#

if the complexity grows beyond what you can type, it might be too complex

paper echo
#

so much less shit to keep in my brain

#

if i just let mypy/pycharm do it for me

slim island
#

triple nested structures sounds like the kind of things you shouldn't be doing

red solar
#

also you can make your own types that combine other types

paper echo
#

that too

slim island
#

dataclasses and typing.namedtuple make life very easy

undone hare
#

You can also create a T object to avoid typing triple nested tyephints

brazen jacinth
#

For example, at my company there was a huge already existing codebase, where i wanted to enforce typing

#

with time, i just gave up

paper echo
#

@swift imp

import attr
import marshmallow


@attr.s(slots=True)
class Person:
    name: str = attr.ib()
    age: int = attr.ib()


class PersonSchema(marshmallow.Schema):
    name = marshmallow.fields.String()
    age = marshmallow.fields.Integer(validate=marshmallow.validate.Range(min=0))

    @marshmallow.post_load
    def to_obj(self, data: Dict[str, Any]) -> Person:
        return Person(**data)

i do stuff like this all the time for example

#

@brazen jacinth that requires a discussion w/ management

tacit hawk
#

type hinting improves a lot readability and static error detection. Without typehint I feel I am blind

paper echo
#

it's a long effort that requires piecemeal changes and some structure

brazen jacinth
#

to be honest, if docstrings are good, you don't really need hints

paper echo
#

strong disagree

undone hare
#

Yeah

peak spoke
#

When starting development it doesn't help as much because you know the types anyway, but for anyone else or in the future it'll prevent a lot of paint

tacit hawk
#

For small programs you can run it in mind but for big softwares its impossible for me

brazen jacinth
#

don't get me wrong, i like type hints, and use them when i can

undone hare
#

They serve different purposes, docstrings are for the developer, typehint for the IDE/tools

brazen jacinth
#

but it's not something that is needed, merely improves life

peak spoke
#

Docstrings specified types for a fair amount of time, and still do in some formats

paper echo
#

but if you can omit types from the docstring thats great to me

brazen jacinth
#

true

karmic slate
#

Python 3.10 looks good but what about 3.12

paper echo
#

🤔

peak spoke
#

only thing we know about 3.12 is the possible rough release schedule

undone hare
#

Is there any PEP even targeting 3.12

brazen jacinth
#

doubt

peak spoke
karmic slate
#

Python 4 also going to be popping

peak spoke
#

and a couple others where it mostly lists the changes incrementally or release peps

slim island
#

is 3.11 a thing? or is it just not relevant to that pep?

undone hare
#

Was going to say except removal of deprecated features :D

#

It is a thing, just not relevant for this pep

slim island
#

ah - sure

karmic slate
#

Is there going to be a py 4 or are they just going to stick with 3.x for future updates?

peak spoke
brazen jacinth
#

well, when a major backwards incompatbile change will be introduced, that'll be the starting stone for py4

peak spoke
#

There are no plans for it yet afaik

undone hare
#

Ah yeah this one is interesting

red solar
#

there's some things in the documentation that say that they're deprecated and will be removed in python4 🤷

#

how would i go about getting something added to python that i don't want to implement myself?

brazen jacinth
#

basically, you write a pep 😛

red solar
#

ah i didn't quite mean as a language change

#

more as an additional feature to a standard library

brazen jacinth
#

stdlib addition?

red solar
#

yeah

brazen jacinth
red solar
#

Typically this is done by sharing the code publicly.
notlikethis

#

i want to get a single function added to re

#

but idk how to implement it yet :/

brazen jacinth
#

🤷‍♂️

#

speaking of the changes in the upcoming minor versions, can anyone give me an ELI5 on the differences between the old LL parser and the new PEG parser

#

formal language theory was never my thing, still, im curious

#

guido seems to have an ardent disposition towards parsers funny enough, he probably has a write up somewhere

red solar
#

Seems like LL is purely context free whereas PEG can be context dependent?

paper echo
#

@red solar cant you at least ask on a mailing list

narrow kettle
#

Look ahead 🤪

red solar
#

oh yeah I guess I can do that

narrow kettle
#

Basically peg can do look ahead recursively

paper echo
#

i truly despise mailing lists but

red solar
#

the mailman web interface makes them bearable

brazen jacinth
#

meaning, it's performance is worse/better?

undone hare
spice pecan
#

Long story short, the PEG parser is more flexible as it can look ahead and stuff like that, while the current LL(1) parser is somewhat limiting, and some of the recent additions required hacky grammar rules due to that. The old parser was built with older tech in mind, and is kind of... outdated, I guess

magic python
#

are random number generators consistent across updates?

undone hare
#

LL(1) is really freakin' old yeah, from a time when 2mb of memory was literally the whole NASA server (1969)

slim island
#

are random number generators consistent across updates?
Provided with the same seed, yeah they would be. Unless otherwise stated

undone hare
#

And yes, the NASA launched people on the moon with a 2mb server

brazen jacinth
#

aha, interesting thanks for the eli

undone hare
#

Point is that in 1969 you couldn't buffer the input and do some lookahead assertions

boreal umbra
#

I just pip installed a library that I'm working on and I can import it, but it can't see any of the submodules. And there's nothing in the top-level __init__ file

supple topaz
#

Sorry can I have an example of usage of this:

if name = 'init':
main()
Thanks

narrow kettle
supple topaz
#

Ok

slim island
#

i'm not entirely sure how/why that doesn't fit this channel. They're not asking for help with a specific piece of code, and it's pretty easy to make the argument that qualifies as an advanced language feature

narrow kettle
#

running a main is an advnaced language feature?

slim island
#

that's not as simple as namemain. It's about the meaning of the __name__ and it's implications - it's not a question I'd guess most people on this server could answer

#

where else would they go to ask that question? #python-discussion is too hectic by design, and it doesn't seem to belong in a help channel, although that might be the best place

narrow kettle
#

i feel like the majority of people here would be able to explain what a __name__ is imo

low lagoon
slim island
#

i don't know what a __name__ is

#

i have no idea what it does beyond namemain

#

and i'm pretty confident with the language

#

like - I just don't see how/why it doesn't fit

brazen jacinth
#

If you ever imported a script you know what it does

narrow kettle
#

its the name of the module, the name is implicitly __main__ when that file is run as the main file

#

hence the == __main__

slim island
#

If you ever imported a script you know what it does
@brazen jacinth

I don't understand the implications of doing __name__ == "__init__". From the sounds of their question, it's a fairly common thing to do - but I'm not sure exactly what you're normally looking to do in the __init__.py

narrow kettle
#

im pretty sure they meant __main__

#

at least thats how i read it

slim island
#

i mean

#

i read it as exactly what they said

#

although, from the sounds of it - it isn't really a thing

brazen jacinth
#

Im gueesin he meant if name is main, aka the classic thing to do to prevent the script from automatically run if imported

narrow kettle
#

i cant really think of a way it would be a thing, but im not the most knowedable py person. maybe there is a reason for it

flat gazelle
#

__init__ as a name is possible, but there is probably never a reason to check for it

narrow kettle
#

i thought it was pretty clear he was talking about the standard way of defining an entry point

slim island
#

alright sure, that makes sense

strange fog
#

@red solar whats the new re function you want to implement, out of curiosity?

red solar
#

__lt__ and __eq__ (but as named functions, not dunders)

strange fog
#

for patterns?

red solar
#

ye

strange fog
#

what would __lt__ for a pattern be based on?

red solar
#

a < b if b matches everything a matches and more

strange fog
#

interesting

#

what would be a use case for such a comparison?

red solar
#

sorting a list of regex objects so that you can attempt to match each of them with a string, without worrying that the string will match a less specific regex before a more specific regex

strange fog
#

nice, i like that

#

is there already a general algorithm for it?

#

or is that the aspect you specifically wanted help with implementing

red solar
#

uhh technically yes... regex -> NFA -> DFA -> subgraph isomorphism

#

i'm sure there's better solutions

#

but it depends on the internals of the re library, which means ideally someone familiar with those would implement it

#

like hopefully re already generates a DFA internally

carmine silo
#

Hey could someone help me with a problem I’ve been having?

red solar
#

(or look at the topical channels)

carmine silo
#

Thanks, this is my first time here

lofty rover
#

so I was reading pep 8 documentation, and came across this: When implementing ordering operations with rich comparisons, it is best to implement all six operations (__eq__, __ne__, __lt__, __le__, __gt__, __ge__) rather than relying on other code to only exercise a particular comparison.

#

I'm not quite sure what they mean by this, and when this should be applied in practice when using ordering operations.

#

the rest indicates: ```To minimize the effort involved, the functools.total_ordering() decorator provides a tool to generate missing comparison methods.

PEP 207 indicates that reflexivity rules are assumed by Python. Thus, the interpreter may swap y > x with x < y, y >= x with x <= y, and may swap the arguments of x == y and x != y. The sort() and min() operations are guaranteed to use the < operator and the max() function uses the > operator. However, it is best to implement all six operations so that confusion doesn't arise in other contexts.```

#

Anyone know what they mean by the top part then?

spice pecan
#

The interpreter will try to work with what you have if the set is incomplete, and the way I understand it, they recommend providing all comparison operators (either manually or with something like functools.total_ordering) instead of relying on the interpreter to improvise in such situations

grave jolt
#

The drawback oftotal_ordering is that it will be slower that implementing it yourself.

lofty rover
#

Ah I see, it's to prevent inconsistencies then when the interpreter does it by itself

red solar
#

It may also be that your ordering is partial, and the ordering provided by the defaulted comparisons will be stricter than what you desired

peak spoke
#

Not much speed difference there

grave jolt
#

Well, it's not that slow, yes

#

but it comes with some overhead, so it's up to you

lofty rover
#

what would an actual example be?

#

I can't imagine coming across this quickly with the code I'm writing

red solar
#

example of speed or different ordering?

lofty rover
#

different ordering

#

is == essentially the same as __eq__ or do I misunderstand?

red solar
#

it is

lofty rover
#

and I want to prevent == to be interpreted as the inverse of __ne__?

red solar
#

yes

#

well maybe

#

maybe you don't, trying to find an example

#

ok take for example NaN

#

if you have NaN and any float, every comparison apart from != returns False

#

so you can't create < based on >=

lofty rover
#

Ah that's clear, nice example.

grave jolt
#

Well, in general, < should be not >=. NaN is a logically inconsistent outlier.

lofty rover
#

Interesting stuff, fun to learn more about python obscurities.

#

Well, in general, < should be not >=. NaN is a logically inconsistent outlier.
@grave jolt from a mathmatical perspective that is inherently true

grave jolt
#

Well, NaN is not equal to itself not just in Python, it's just the floating-point standard.

red solar
#

which tbh makes it simple to check if a float is NaN lol, def is_nan(f): return f != f

grave jolt
#

Well, that's not how it works...

#

Because == for floats should be able to know if either of them is NaN

red solar
#

ok, not f == f, same thing, no?

lone prairie
#

!e print(float('nan')!=float('nan'))

fallen slateBOT
#

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

lone prairie
#

oh. well, it works

grave jolt
#

@red solar equality or inequality of floats needs to know whether either of them is NaN, obviously, because NaNs shouldn't be equal to each other

zenith iris
#

spam

fallen slateBOT
#

:incoming_envelope: :ok_hand: applied mute to @zenith iris until 2020-07-24 22:22 (9 minutes and 59 seconds) (reason: discord_emojis rule: sent 28 emojis in 10s).

alpine thistle
#

Hi, is it possible to get list of class attributes except the ones of a parent class if I don't know the parent class?

torpid bridge
#

!e ```py
class A:
a = 1
class B(A):
b = 2
b = B()
print(b.class.dict)

fallen slateBOT
#

@torpid bridge :white_check_mark: Your eval job has completed with return code 0.

{'__module__': '__main__', 'b': 2, '__doc__': None}
red solar
#

what if the class has no __dict__?

torpid bridge
#

Then presumably it has __slots__, I think

heady mauve
#

I'd like to try something real quick

#

!e print('hello')

fallen slateBOT
#

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

heady mauve
#

Hmm...

torpid bridge
#

If it doesn't have either dict or slots, you're probably out of luck

red solar
#

hmm there must be a way to do it with inspect though

#

lol

torpid bridge
#

Short of inspecting what it does with __getattr__

alpine thistle
#

@torpid bridge Thank you so much, this is exactly what I needed

torpid bridge
red solar
#

Check out PyPy. It is every bit as fast as the fastest Javascript engines
like V8.

#

is this a valid statement?

swift imp
#

Does anyone have any literature on the various applications of descriptors?

charred wagon
#

What are the naming conventions for TypeVars? I see single letters used but I think those are woefully vague.

#

Cause one would have to make assumptions about how the type relates to the class. Is it the type for what the class stores? Is it the type for the object it is created from? Etc

grave jolt
#

hm

#

Well, if you name it in PascalCase like ItemType you can confuse it with a normal class

charred wagon
#

Yeah, I should have mentioned I've seen that. It's pretty broad

grave jolt
#

@wanton aspen are you sure this belongs here?

#

<@&267629731250176001> ^

north root
#

!ban 733392725109637202 spamming random things

fallen slateBOT
#

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

grave jolt
#

thanks

charred wagon
#

I've seen Google's style guide for Java and they suggest appending Type or just T to the end of a name

#

I like the latter personally

grave jolt
#

In Haskell, type parameters are in lower case. I think it might make sense in python as well. I don't think it can bring confusion, because the context for functions/variables is orthogonal to type parameters.

#

so

class Repository(Generic[e]):
    ...

class Repository(Generic[entity]):
    ...
charred wagon
#

That's quite interesting

#

In a certain way it does make sense, since they're variables after all

#

But alas, I am a slave to PEP 8

#

(not really)

swift imp
#

Is there a python version of the gang of four book?

grave jolt
#

Isn't it supposed to be language-agnostic?

swift imp
#

The examples are all c++ and Java

grave jolt
#

It doesn't mean that the concepts don't apply to other OO languages

swift imp
#

Yeah but they're harder to follow

grave jolt
spark magnet
#

@swift imp the patterns might not apply to python

#

and some of them are bad ideas, like Singleton

grave jolt
#

maybe some patterns might not apply because of dynamic typing, multiple inheritance (Java doesn't have it) or Python features like decorators

#

even if singletons were a good idea, I don't think they make sense in Python (they can be emulated as a module or as a class that's never instantiated)

swift imp
#

What the heck is a Singleton

grave jolt
#

it's a class that only ever has one instance

swift imp
#

Oh

#

What the hell is the use of that

grave jolt
#

i myself have no idea at all

visual shadow
#

Your boolean True and False. A None. Singletons.

grave jolt
#

well, None

visual shadow
#

They will always pass an is check

#

No matter where in the code they originate from. Since it's the same object.

spark magnet
#

a singleton is a class that lies: you think you are making objects, but it always gives you the same one.

#

it's a hidden global.

visual shadow
#

Hah, that's a nice way of putting it

grave jolt
#

NoneType and bool are probably fine because they are pure (immutable and don't give access to some state).

swift imp
#

Oh God why is the only version of that book on libgen a god damn epub

grave jolt
#

it's on amazon kindle :)

visual shadow
#

Take the epub and use some format converter.

swift imp
#

I'll buy it, if I like it

#

But I always pirate the book first

#

Unless it's so highly rated that everyone says it's amazing

grave jolt
#

Alright, we're getting off-topic

visual shadow
#

Probably might deviate from topic if we continue that discussion

swift imp
#

Yeah lol

grave jolt
#

NoneType and bool are fine as singletons because they are simply enums/algebraic data types.

#

But a singleton config is bad because now stuff that's using a config is not testable, and you can't customize config getting.

#

One pattern which is definitely probably not applicable to python (and probably to C++ nowadays?) is the Strategy pattern.

peak spoke
#

They're also not used in the sense that you're repeatedly creating the single instance, but instead are global everywhere

grave jolt
#

The Strategy pattern is just a function, as I understand it. Although it might be a collection of functions 🤔

visual shadow
#

Singletons, from what I understood, are also great for managing state for a resource that must stay in sync throughout the code. But I'll admit I never had to use one

swift imp
#

This book looks so over my head

narrow kettle
#

I use a Singleton for basic config stuff

grave jolt
#

Disclaimer: I haven't read it

swift imp
#

Architecture Patterns

visual shadow
#

I don't know whats the strategy pattern

grave jolt
#

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

visual shadow
#

English is hard.

grave jolt
#

sort(key=...)

visual shadow
#

Ah. I see

grave jolt
#

Here you're parametrizing sorting by a custom algorithm

#

From what I've seen/read, it's usually done as a refactoring when you have lots of arguments passed into one function.

swift imp
#

Let's go there then

#

Please, I like this talk

leaden mortar
#

so I have a list of dictionaries:

list1 = [{key1:value1, key2:value2}, {key1:value1, key2:value}, {key1:value1, key2:value2}]

I want to add a third key in all dictionaries with value that'll be the sum of existing 2 values.

spark magnet
#

@leaden mortar for d in list1: d['key3'] = d['key1'] + d['key2']

leaden mortar
#

thank you

grave jolt
leaden mortar
#

ok

unkempt rock
#

hey whats up. i got a problem, when i put. type: "" it doesn't shows me options for the status and i already put setPresence, can someone help me? please

grave jolt
unkempt rock
#

oh ok thx

whole dagger
#

What is best platform to do python coding - Idle, Pycharm or ML Studio ?

torpid bridge
#

Pycharm, probably

#

I would not suggest IDLE to anyone that isn't a beginner

whole dagger
#

@torpid bridge okay!!

candid glen
#

Id say Pycharm and Spyder, though I'm not a pro in any way

torpid bridge
#

advanced editors like sublime text and vscode are often suggested

undone hare
#

Tbh I wouldn't recommend IDLE even to a beginner

ornate oyster
#

i think there's a raid going on lmao

undone hare
#

IDLE is just the terminal interactive session outside of a terminal, it can became a mess to manage larger projects

brazen jacinth
#

sort(key=...)
@grave jolt does this count as the strattegy though, afaik this is more related to the comparable/comparator type, as the sort is always the same afaik (some variant of timsort)

slim island
#

Mu or Thonny are two good beginner recommendations

unkempt rock
#

i have a question

#

so

#

am i allowed to type in the code

#

in here

#

yeah i suck

#

idk how to debug this

#

but

#

class Solution:
def isPowerOfTwo(self, n: int) -> bool:
def isPowerTwo(n):
if n == 1:
print('true')
if n%2 == 0:
isPowerTwo(n/2)
else:
return False

#

as n set to 1

#

n = 1

slim island
unkempt rock
#

thonk*

#

ok

slim island
#

https://www.python.org/dev/peps/pep-0505/

What are the implications for a pep being deferred? Are they usually dead in the water, or do they often come back? I find myself dreaming of having null aware operators, and am curious as to what the chances are. Also, is there any easy way to find discussion about a pep?

steady moss
#

hi'

deft pagoda
#

you can subscribe to python-ideas

#

maybe they'll talk about it, maybe with the new parser someone will work on none-aware

slim island
#

The problem is that most of the stuff that goes on in the mail lists I don't care about - I'm only really interested in the stuff that seems interesting/useful to me, and most of the mail list isn't

#

also - i'd really like to read discussion about that pep retroactively, it was originally proposed back in 2015

brazen jacinth
#

that pep does indeed look interesting

spice pecan
#

It's a less verbose alternative to x if y is not None else z, I think it would be really convenient

slim island
#

it becomes a lot less verbose if you're doing something like dealing with janky json

#

where you have that if not None else pattern everywhere

brazen jacinth
#
if config and config.auth and config.auth.username
vs
if config?.auth?.username

a contrived example

spice pecan
#

And that's a scenario where false-y values are out of the question

#

imagine if they weren't

ornate oyster
#

hello

deft pagoda
#

the pattern matching proposal along with none-aware can make a lot of chaining more comfortable

lunar trail
#

@unkempt rock This isn't a help channel

magic python
#

What's the definition of a "top level package"

peak spoke
#

The top initialized package which has all the modules of that app under it

swift imp
#

Why the heck is Guido toying with the idea of making print a keyword again

narrow kettle
#

optionally i think

#

and its kinda like a "the parser can do this now" no?

swift imp
#

That's how he presented it but why even

#

That's just gonna be so confusing

#

For all of 3 it will be a function and the all of sudden in 3.10 a keyword?

deft pagoda
#

doubt it, the idea seemed to be mostly shot down

radiant fulcrum
#

I feel like it would cause alot of confusion tbh

left pollen
#

sir i have some doubts ,i had watched your python web automation video,i tried to automate google meet,everything is working well except when i join the meet with the join id,i switch to the child node correctly and interacted with evry element,algood,except the alert box on the chld window can not be closed,it says no such alert,the alert requests for cam mic permission whcih in want to dismiss,Stuck for two days? used wait methods too still no luck?any suggestion?

grave jolt
#

@deft pagoda the only advantage I see is that it will encourage non-toy projects to use proper logging... maybe

slim island
#

the PEP wasn't about making print a keyword, just pointing out that it was possible right?

spice pecan
#

yeah

#

It was just an example showing what the new parser is capable of

magic python
#

i've heard that using shell = True in subprocess is a no no, but i've never understood why it's any more dangerous than just using the shell in general, or a shell script, or whatever else... I've seen people say not to use it a lot but haven't seen something that really argues that it's any worse than the thing it's basically emulating, a shell

visual shadow
#

Python docs take a stance on it based on shell injection

#

So, the pairing of shell=True and unsanitized input

magic python
#

I don't understand what makes that worse than just using the shell though

#

unless that's part of the argument, don't use the shell

visual shadow
#

Nah. Basically if someone has physical access to your computer, it's a moot point

#

But when you give someone a python program that interacts with user takes their input.. You see where this is going?

#

You're introducing a vector of attack via the python script that goes beyond just physical direct access to running the shell or terminal.

magic python
#

right - so people often moan about this but i rarely see much said, though i'm not appreciating the injection part enough. It seems that using it within a script as a convenience to use shell functionality is fine

visual shadow
#

Indeed.

magic python
#

right - so there are particular instances when it's dangerous, ie user programmes and whatnot, but on a devs system I have never appreciated the drama around it

#

at worst it seems to be a code smell for using a shell function which could be done with a default python module

visual shadow
#

It's the combination of unsanitized input and that argument that makes it a problem. As far as I'm aware, there's not a problem if unsanitized input is not involved.

#

The code smell argument is sound though. Why do things in a manner that can be done much safer?

#

I assume perhaps that's why it became such a big talking point.

magic python
#

right - the main reason that I would use it would be things like gsutil or whatever, that are much easier from the shell. Most of the time these can be done with subprocess.run([ ... gsutil args ]) anyway, so shell=True isn't always needed there either... I think i'm just annoyed that I'm told it's categorically wrong when it doesn't seem to be lol

raven ridge
#

unless that's part of the argument, don't use the shell
@magic python it's not that it's categorically wrong - if you need to use a shell, or using a shell makes what you're doing much easier, it's the right tool for the job. But using a shell when you don't need one exposes you to all of shell's disadvantages unnecessarily. Like problems with handling filenames containing spaces. Or what happens when a filename contains a $ symbol. Or a backtick. Or any other shell metacharacter.

#

Basically, using shell=true makes it so that someone reading your code needs to know both Python and shell to know if it's correct, and it makes it so that it can break catastrophically if the user passes you input that is special to the shell.

#

Even if the only thing the user is in control of is a filename that you're passing to the shell, if they give you a filename like foo$(curl http://some.malicious/script | sh)bar they can make you run arbitrary code when you thought you were doing something safe.

mystic cargo
#

so if I don't take any user input can i use shell = True?

#

for a simple script

#

assuming no one messes with it

raven ridge
#

Sure. As long as you know exactly what args you'll be passing and how the shell will interpret them, it's perfectly safe (although possibly unnecessarily complex). It's only unsafe or potentially incorrect when the arguments could contain shell metacharacters.

#

But keep in mind, that even means it isn't safe to do something like read a list of filenames in some directory on disk and run something with shell=True for each of them. A file with a name containing a space will make your command do something different, which you don't want.

#

Also, it's worth noting that shell=True executes in a different sort of shell on Windows than on Unix, and even on Unix it could give you dash or bash or busybox sh - so it can also easily lead to portability issues.

feral bane
#

there are only a couple of things that can be done semi-portably with shell=True

#

redirection of input and output, pipelines, and automatic word splitting of the command line

#

command line word splitting can be done with shlex, and redirection and pipes can be done reasonably easily with other features of the subprocess module

#

beyond that, you're doing things that are highly specific to whatever windows, unix, or other operating system [are there any other operating systems supported by python anymore?] shell you're running on anyway, and it's better to figure out a way to do those things portably with python code instead

boreal umbra
#

In a help session, I made the statement "Python is designed for readability, and if you're going for an algorithm where the speed of operations like list deletions are mission critical, chances are you should be working with C++ or something."

List deletions were just the topic at hand. The point I really want to make is that you usually wouldn't use pure Python if performance is that important for what you're trying to do. How wrong am I?

torpid bridge
#

Python makes a significant amount of tradeoffs in exchange for greater dynamicity. For example, it compiles to bytecode during runtime, does not have compilation units, does not go through llvm, methods are looked up when used, and most everything is a hashmap (locals/globals/classes/etc).

On one hand, this means every time you access attributes or insert things into a list you're essentially dealing with a HashMap<str, Arc<Box<dyn PythonObj>>, and accesses to attributes can trigger function calls, which requires a global interpreter lock to prevent issues (GIL), and a large amount of allocation (each object in a list is behind its own reference counted pointer IIRC).

However, this means lists can contain anything, you do not need to generally use generics, polymorphic code is relatively easy to write, inheritance and inheritance-based testing is possible, decorators are clearer and much more concise than macros, and you can write in one line what may take 3, 4, 5 or more in other languages.

Because of these tradeoffs I find python to be a very good development language. It will not get in your way excessively, it makes it easy to do things that advance your knowledge and data model of your application, and interfaces with anything and everything without requiring you to know your nits. But it does come with a cost.

For many high-performance loads, pure python runs at ~100x slower than comparable C. We can get closer by hooking into modules such as numpy, which take advantage of C's performance and hide some of our loops/matrix transforms/raw math inside of it. This gives us a potent boost, and in most cases is more than good enough.

However, because of that, there are a variety of situations where performance is king and python is not appropriate. Video/audio decoding/muxing/capturing, for example. If these are to be done in python, they should be done via extension, since the goal is smooth frames and processing thousands of pixels per second.

#

( holy wall of text, sorry. But I generally think you've got the right idea )

#

I kind of see a few kinds of optimizations you can apply to your code:

  • Algorithmic (IE: reducing N^2 to log(n)),
  • caching (don't recompute this, always recompute that),
  • reducing what needs to be done (only flip bit x),
  • taking advantage of additional cpu instructions (MMX/SSE).
    Python is good for the first two, but if you find yourself needing ( you should test this, premature optimization is the root of evil ) to do the last two you should consider going with a language that exposes those directly.
undone hare
#

^^ this message clearly deserves a pin IMO lemon_hearteyes

torpid bridge
#

For example, I've got an algorithm I use to display a spreadsheet for debug viewing in the terminal, autosizing the clip of displayed columns, showing headers, and line numbers

It's very short compared to what I'd have to write in, say, rust, but it gets the job done. It's also O(N^2M), which at first glance isn't great. However, M is the number of columns of the terminal.. max, say, 400, and N is the number of spreadsheet columns, max, say, 50. That's about 40k operations once per table, and even in python that's basically nothing for the absolute maximum. In practice, printing to the terminal takes longer. I could do all sorts of optimizations here, but it's not worth it. In addition, I'm using min(), max() and index(), all of which lower into C in python, so its triply not worth it.

undone hare
#

That's the beauty of 2020, most fields doesn't require implementations to be really fast, just need to do the job, that's why python is really good in most of those fields

torpid bridge
#

As I see it, these days development is expensive, and computers are cheap

noble birch
#

!code

fallen slateBOT
#

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print('Hello world!')
```

Note:
These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them

This will result in the following:

print('Hello world!')
undone hare
#

As I see it, these days development is expensive, and computers are cheap
@torpid bridge

That reminds me of electron in some way, companies prefer to sacrifice a ton of resources, but not have to make their employees learn "normal" GUI frameworks, like Kivy or whatever

fading breach
#

hi

slim island
#

Hi @fading breach. This isn't really the best channel for introductions/chatting, it's about quite a specific topic, you might get a better response in #python-discussion or offtopic

fading breach
#

okai

#

this channel is for bugs and specific code related qns right?

slim island
raven ridge
#

How wrong am I?
@boreal umbra Not. Python is designed for readability and maintainability, not performance.

unkempt rock
#

how do i start SQLmap

#

.help

#

┬─┬ ノ( ゜-゜ノ)

#

(╯°□°)╯︵ ┻━┻

slim island
rotund quest
#

Hello everyone

So, I'm new to python and I saw this sample Flask app in their documentation...

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

Why is the reference to the Flask class, app, prefixed with an @ symbol in @app.route('/')?

Finding the answer online was harder than I thought it would be 🧐
Is there a place or documentation somewhere where these possible prefixes are described?

flat gazelle
#

that is a decorator

#
@function
def other_function():
    ...
```is roughly equivalent to
```py
def other_fucntion():
    ...
other_function = function(other_function)
rotund quest
unkempt rock
#

hi everyone

#

im new here

brazen jacinth
unkempt rock
#

oh ok thank you 🙂

open anvil
#

what is the best language to code plugins

brazen jacinth
#

what kind of plugins

#

browser plugins, minecraft plugins, vscode plugins, vim plugins?

#

very broad term, also probably not the right channel for it

languid dagger
sharp belfry
#

@languid dagger where can i see the channel topic?

unkempt rock
#

anyone want to help me make a python monopoly?

languid dagger
#

@unkempt rock Don't spam your message and also read mine literally just above

#

@sharp belfry On PC it's just above next to the channel name. Mobile you have to tap the channel name

sharp belfry
#

@languid dagger oh got it!!

boreal umbra
#

@torpid bridge that was a great read, thank you very much

#

I agree that it should be pinned.

flat gazelle
#

what would you think about type() returning the current class, in the same vein super() works.

class U:
    def own_name(self):
        return type().__name__
``` for example.
boreal umbra
#

why?

flat gazelle
#

sometimes, you need to get the current class, especially outside methods and it is quite annoying to do

boreal umbra
#

I think self.__class__ is faster

#

though self.__class__.__name__ is annoyingly wordy

wicked haven
#

Hii everyone

gloomy harness
#

what's the reason not to use self.__class__.__name__?

deft pagoda
#

there's a reason to use one and not the other, but i forgot it and it's super corner case -- so i usually do the chaining

#

though i'm not super consistent about it

full talon
#

can anyone reccomend any good grammar correction libs/apis?

slim island
brazen jacinth
#

what do you mean by grammar correction, python grammar?

full talon
#

oh sorry

brazen jacinth
#

nevermind then 😄

slim island
#

Well. I guess this could be the right channel depending on what exactly you mean I guess. Read the topic and if you think it fits, go for it

full talon
#

no not really

brazen jacinth
#

anyway, i'll post it here as a bonus as the channel is a bit less saturated, if you're interested in cpython internals, specifically the bits before the bytecode generation itself (AST generation)

sturdy timber
#

I sort of want to try out some project involving working with ast, ast.unparse() being added in 3.9 is also pretty interesting

brazen jacinth
#

if you ever used 2to3, or that static type checker... bandit yea

#

they use ast manipulation

deft pagoda
#

we did something with lemon with ast.unparse

#

used unparse to programmatically change a bunch of function calls

brazen jacinth
#

wise comments

sturdy timber
#

Oh I remember watching you guys do that salt, I had no idea what was happening, but it looked extremely cool

deft pagoda
#

i have a ast pretty printer too, if you're interested

brazen jacinth
deft pagoda
#

ex:

In [3]: pp('def f(n=1): \n    for i in range(n):\n        print(i)')                                                                                                                                                     
FunctionDef
├──f
├──arguments
│  ├──arg
│  │  ╰──n
│  ╰──Constant
│     ╰──1
╰──For
   ├──Name
...
wide shuttle
#

Yeah, that's a nice tool. You should package it and publish it to PyPI.

deft pagoda
#

never actually done it, i'd have to read something or something

wide shuttle
#

It's not actually that difficult (and shouldn't be for the tool you wrote)

#

Could be cool to have it as a script as well, which means you'd be able to run it from the command line directly

#

pp "code" or pp file

deft pagoda
#

the tree would be insane for some reasonable .py file

wide shuttle
#

Probably not pp though

#

that's true

deft pagoda
#

might be fun to see

#

whats that rich text thing for the terminal, could be nice to pipe to

#

oh, rich is the name of it

nova thistle
#

so i've seen that functions in some modules take a another function as an argument

#

how do i do that?

deft pagoda
#

attribute? or argument?

nova thistle
#

lets say i have function called Transformer()

#

i want it to take in another function as an argument

spice pecan
#

If you want to pass a function as an argument, you don't have to do anything special, functions are also objects

nova thistle
#

i see

#

is there an example i take a look at

spice pecan
#
def high_level_func(func):
    func()


def regular_func():
    print('Hello!')


high_level_func(regular_func)```
nova thistle
#

cool

#

thanks

brazen jacinth
#

tbh better then

>>> ast.parse("a = 2 + 1", mode="exec")
KeyboardInterrupt
>>> node = ast.parse("a = 2 + 1", mode="exec")
>>> pprint.pprint(ast.dump(node))
("Module(body=[Assign(targets=[Name(id='a', ctx=Store())], "
 'value=BinOp(left=Constant(value=2, kind=None), op=Add(), '
 'right=Constant(value=1, kind=None)), type_comment=None)], type_ignores=[])')
#

seems like a good lib

#

i encourage you to upload it as a package

deft pagoda
#

i'll try to do it tomorrow, i'm close to my bedtime

spice pecan
#

@unkempt rock I guess you could just make a wrapper class and decorate your function with it

deft pagoda
#

making a package makes me want to add a few more features to it

#

it's pretty barebones

brazen jacinth
#

is there any lib to visualize a control flow graph from a ast?

#

that'd be a nice addition

deft pagoda
#

there's something like that for js i think?

spice pecan
#
class FalseyFunc:
    def __init__(self, func):
        self.func = func
    def __get__(self, *args):
        return FalseyFunc(self.func.__get__(*args))  # Support for bound methods
    def __bool__(self):
        return False
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)
#

Something like that @unkempt rock, you can then do

>>> @FalseyFunc
... def some_func():
...     print('yo')
...
>>> some_func()
yo
>>> bool(some_func)
False
>>> class Example:
...     @FalseyFunc
...     def method(self):
...             print(self)
...
>>> Example().method()
<__main__.Example object at 0x000002762B552940>
>>> bool(Example().method)
False```
snow perch
#
class Engine:
 def __init__(self, maker, cc):
 self.__maker=maker
 self.__cc=cc
 def __str__(self):
 return f'Engine maker: {self.__maker}, volume: {self.__cc} cc'

eng = Engine('Mitsubishi', 2000)
print(eng.maker, eng.cc)
#

can anyone explain

#

?

unkempt rock
#

@snow perch Explain what?

snow perch
#

this code:(

unkempt rock
#

The indentation is wrong, first off

#

Also, this isn't the right channel for this I believe

snow perch
#

hmm ok

#

!

still river
#

how can i run my program as background process?

grave jolt
#

depends on what exactly you want

#

@covert pier This is not a help channel, please read the channel description. For help, check out #❓|how-to-get-help.

covert pier
#

thanks

clever sequoia
#

I was trying to understand the pointer notation in zip(*grid) where grid is a nested list, and ended up reading a really cool tutorial https://realpython.com/pointers-in-python/
But I am still unsure what that * really means

In this step-by-step tutorial, you'll get a clearer understanding of Python's object model and learn why pointers don't really exist in Python. You'll also cover ways to simulate pointers in Python without the memory-management nightmare.

grave jolt
#

@clever sequoia This is not a help channel, please read the channel description. For help, check out #❓|how-to-get-help.

pearl river
clever sequoia
#

Thanks. It's confusing choice of notation

spark magnet
#

Python and C are different. Just because C uses * for something, it's ok for python to use it for something else.

grave jolt
#

I hope C++ will get more ways to use & over the years

radiant fulcrum
#

& just reminds me of Rust's Borrowing system

grave jolt
#

...right not & is used as

  1. a reference type: const int& a = 4;
  2. bitwise AND: 0xabc & stuff
  3. logical AND: thing && stuff
  4. rvalue reference type: int stuff(int&& thing)
  5. in lambdas to denote capturing a reference: [&x](){}
  6. referencing a value to store in a pointer: int *p = &x;
white saffron
#

can anyone help e with this

grave jolt
#

@white saffron This is not a help channel, please read the channel description. For help, check out #❓|how-to-get-help.

white saffron
#

im on mac and using visual studio code and this will not work

#

ok thank you

worldly venture
#

!ban 279017706228023297 Spam

fallen slateBOT
#

:incoming_envelope: :ok_hand: applied ban to @lyric lichen permanently.

spark magnet
#

people who can't make things just like to break things.

worldly venture
#

hah, indeed

celest spade
#

quick question i am able to run django-admin on my computer but when i say django admin startproject (projectname) it says no django command found

grave jolt
#

@celest spade This is not a help channel, please read the channel description. For help, check out #❓|how-to-get-help.

#

oh, well

flat gazelle
#

Oops, thought this was general

grave jolt
#

Well, it's okay to answer it if it's quick, don't delete the answer

celest spade
#

kk

grave jolt
celest spade
#

sure

cinder dirge
#

why there are no switch statements

narrow kettle
#

they are coming

gloomy harness
#

hopefully

#

pep cantremember

flat gazelle
#

Well, pattern matching is. Switch in the C sense is not

#

622

gloomy harness
#

yes that’s it

narrow kettle
#

pattern matching is cooler anyways

gloomy harness
#

agreed

flat gazelle
#

Exactly. C style switches are bad

gloomy harness
#

And if they were implemented in python, I feel like there’d be a lot of misuse where someone should use a dict instead

charred dirge
#

I was trying to understand the pointer notation in zip(*grid) where grid is a nested list, and ended up reading a really cool tutorial https://realpython.com/pointers-in-python/
But I am still unsure what that * really means
@clever sequoia If it helps, you can think of * as being the same as ... in Javscript/Typescript (though you need to use ** for dictionaries).

grave jolt
#

Would it be possible to warn a user when they're using string interpolation in a query?

#

Something something inspect?

#

I think it would be a great idea, and it should skip the check with the -O flag

#

I think it would be possible with inspect.getsource and ast

#

And if you know what you're doing (like inserting a name of a database for some reason), you can put a

# i-know-what-i'm-doing

comment

narrow kettle
#

id still prefer a way to do fstring syntax FOR sql

grave jolt
#

That would require the ability to create custom sigils like in elixir

#

creating a special syntax just for SQL is way too specific

#

people sometimes say that r"..." is a regex string, but that's not true, it's a raw string

unkempt rock
#

im-a-skid

peak spoke
#

regex is one of its main purposes, I've seen some people differentiate between r and R, where one is regex and the other are the other things

cinder dirge
#

regex purpose is to inflict suffering to future mantainers

grave jolt
#

well, there's a readable version of regex (with whitespace and comments)

peak spoke
#

A simple few char regex can also be quite a bit more powerful than multiple lines of python code

#

While remaining fast which can be a big factor for string processing

narrow kettle
#

creating a special syntax just for SQL is way too specific
it wouldnt have to be just sql

#

sql libs could USE it tho

paper echo
#

regex was perfect for perl

#

powerful tool that is easy to abuse

#

that said regex is also a bit like perl in that once you're used to it you can read even really gnarly stuff

peak spoke
#

Don't really agree there, you can get the basic groups quantifiers, non capturing groups etc in a few hours but regexes with lookaheads and things like that will still be very confusing

#

Some of the patterns I've seen when solving a problem were borderline esoteric to me while being considered a good solution

swift imp
#

Regex is so powerful it's the key tool in sequencing dna irrc

#

But yeah, except for simple ones, I always have to use a website

narrow kettle
#

theres a dude on the c# server who wrote an entire math library in regex

feral cedar
#

how

narrow kettle
#

you tell me lmao

feral cedar
#

wtf

short merlin
#

Whats a good design pattern when your code is repeating itself except for a few differences? Here I wrotes some psuedocode that is looking an a website for two different files, then downloading them and verifying that theyre there, then setting their status to Success. Its the exact same process for both files except the values are different. Then below I have a potential solution - create dictionaries for each file with all the arguments needed and then just loop through the array of dictionaries. However this feels messy to me too because its so arbitrary to know what arguments would be in your dictionaries. Is there a better design pattern to accopmplish this?

#

all my arguments in this class are becoming these objects and its confusing to tell what in the objects and what they are supposed to represent other than just "what I need to make my for loop work"

clever sequoia
#

Thanks @charred dirge

red solar
#

@short merlin if you know what keys you’re going to have for your dictionary, maybe create a data class instead?

paper echo
#

@short merlin sometimes there is no design pattern. sometimes you can extract common logic to individual functions

short merlin
#

ok thanks everyone

#

ill just write it as is

paper echo
#

(A "pyproject.toml" file was found, but editable mode currently requires a setup.py based build.)
is there any fix for this in the pipeline somewhere 😦

raven ridge
#

What build backend are you trying to use?

jaunty lark
#

Do people teach python language in this discord server?

grave jolt
#

@jaunty lark If you have a specific question, just go ahead and ask it. Not in here though (read the channel description), check out #❓|how-to-get-help

paper echo
#

@raven ridge poetry

#

I looked at some github issue discussions and it seems like we aren't really close to a resolution

#

I think there is a way to generate a setup.py from pyproject.toml, I should just use that or write my own script to do it

raven ridge
#

I'm still so annoyed by the fact that poetry can't be built from source that I refuse to look any further into it.

#

between that and the fact that there are 650 open issues on the poetry repo, I'm pretty convinced no one should be using poetry. It doesn't appear to be well maintained, and for a build backend to itself have fundamentally unresolveable build dependencies makes me think it's not being designed nearly as carefully as an integral part of the Python build ecosystem needs to be.

paper echo
#

wait, what

#

i didnt know about this

#

thats actually quite a bummer

#

i was really enjoying not writing setup.py files

#

as well as the poetry cli

deft pagoda
#

i mean kivy has more than that and i still love it

lost rain
#

engine.setProperty('voices', voices[0].id)

#

i wnt to get zira voice

#

but i arent able to get

#

when i play voice in loop

#

zira voice plays

#

but when i do indexing

#

it didnt come

deft pagoda
grave jolt
#

Could we please have a channel for bikeshedding about style choices? 👀

#

PEP8 recommends exactly one line between methods in a class. I tend to separate each method in a few steps, and those steps get an underscore because they're kind of not intended for outside use. Does it make sense to put one line between sub-methods and two lines between chunks of methods?

spice pecan
#

I think that's fair, yeah

#

You could denote chunks of methods with comments, that'll let you increase visual space between them without technically breaking the pep as well

grave jolt
#

I don't care about technically breaking the pep

#

On the other hand, I could define steps as inner functions.

spice pecan
#
class Sample:
    # First method
    def method(self):
        self._helper_a()
        self._helper_b()
    
    def _helper_a(self): ...
    
    def _helper_b(self): ...
    
    # Second method
    def other_thing(self):
        self._helper_c()
        self._helper_d()
    ...

Something like that should be both PEP8-compliant and properly visually grouped

#

On the other hand, I could define steps as inner functions.
That should work too

hallow burrow
#

I can concatenate two strings just by typing them next to each other in Python 3.7.7 like this >>> "a" "b" 'ab'

#

Does anyone know why?

#

It seems a bit bizzare that this works

grave jolt
hallow burrow
#

I'm not asking for help, though?

grave jolt
spice pecan
#

It's a feature

flat gazelle
#

it works only for literals and exists so that you can easily split strings across multiple lines like so

("Hello "
 "World")
hallow burrow
#

OK, it just seems weird to me as I was always taught to use +

#

Thanks

grave jolt
#

It's used to split a long string like an SQL request across lines.

snow perch
#
def has_digit(n,digit):
    return digit in str(n)
print(has_digit(1234, "5"))   
#

in line 3

#

whats the error?

grave jolt
#

!e

def has_digit(n,digit):
    return digit in str(n)
print(has_digit(1234, "5"))   
fallen slateBOT
#

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

False
grave jolt
#

🤷‍♂️

deft pagoda
#

maybe old python version

still river
#

how can i eject the cd-rom with py

#

is there any cmd command?

broken crescent
#

do u guys are beginners?

grave jolt
#

@still river This is not a help channel. Please read the description of the channel. If you want help with a specific question, use #❓|how-to-get-help

Discussion on the use cases, implementation and future of the Python programming language including PEPs, advanced language concepts, new releases, the standard library, and the overall design of the language.

strong basalt
#

+1

shy belfry
#

When implementing my own version of a set, what are the magic methods I should include to be able to utilize all the features one would come to expect?

#

I want a simple bounded set that limits items to a given number, so far I've got the __len__(), __in__() as well as __iter__(). Is __next__() also one or should that only be for ordered lists?

#

And I suppose remove() and add() as well?

spice pecan
#

__next__ is for iterator objects, you don't need it in your set class

flat gazelle
#

extend the MutableSet ABC

shy belfry
#

extend the MutableSet ABC
@flat gazelle huh... didn't know that existed. Thanks!

#

Then I suppose PYC will help me implement all the expected methods?

#

OHHH... Thanks. I was a little skeptical, haha. Felt like the right place to ask this kind of a more abstract question.

flat gazelle
#

python 2 docs should not be used

shy belfry
#

Thank you! ^^

#

Wow, there's quite a lot of them, haha.

#

Mainly the subset/superset stuff.

#

Are all those just implemented by name?

#

Or is there magic methods as well?

flat gazelle
#

< <= => > is __lt__, __le__, __ge__, __gt__

shy belfry
#

Ahhh... I see. Just refer one to the other?

#

What's more conventional? Implementing the magic methods fully or the named ones?

flat gazelle
shy belfry
#

Woah, that's cool! I'll use that!

flat gazelle
#

you may want to override some of them for performance though, depending on your set impl

shy belfry
#

Ahh... I see, that makes sense! I'll start off with implementing the basics and then add the other methods if I notice any downsides.

narrow nexus
#

some countries have their states
some countries do not have their states

random violet
#

can I know where is the problem please?

myList = ["One", True, 3, "Alex", 0.193, "Sam", "Two", 5, 7]
print(f"Hello :  {myList.index("Sam")}")
narrow kettle
random violet
#

oh ok

cinder plover
#

i have a problem i use pyinstaller to make a .exe file but everytime i try sending it to my friends it says it is a virus and it doesnt let them download it... Any ideas??

spice pecan
#

@random violet you have to use different kinds of quotes if you have string literals inside f-strings

#

otherwise you're closing the f-string

#
f"Hello: {my_list.index('Sam')}"```
that should be fine
lean garnet
#

Hello, if I try to print datetime.now in what format would the date get printed out?

loud summit
lean garnet
#

Oh sorry

sinful saddle
#

Is there a preferred way to extend lists (i.e., to add v, n times, to l)? Namely,
l += n * [v] vs. l.extend(v for _ in range(n))?

spice pecan
#

+= is internally a call to extend, but there's a difference between multiplying a list and using a list/generator comprehension

#

[v] * n will evaluate [v] once and then make a list of n references to the same object

#

v for _ in range(n) will evaluate it n times and populate the list with (potentially) different objects (still depends on what v is)

deft pagoda
#
In [33]: [choice(range(10))] * 10                                                                                                                                                                
Out[33]: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

In [34]: [choice(range(10)) for _ in range(10)]                                                                                                                                                  
Out[34]: [5, 9, 7, 2, 7, 3, 1, 2, 0, 3]

sinful saddle
#

Ah. So if the value is a static value (e.g., from a separate list) then both calls are the same, but if v itself is not static then the two are different

spice pecan
#

If you need to evaluate the expression multiple times (such as random or if you need to generate separate mutable objects), use a comprehension, if you don't, you can just use multiplication

deft pagoda
#

the mutable example would be good to

spice pecan
#

the tic-tac-toe one

#

[[0] * 3] * 3 vs [[0] * 3 for _ in range(3)]

deft pagoda
#
In [35]: a = [[]] * 5                                                                                                                                                                            

In [36]: a[0].append(1)                                                                                                                                                                          

In [37]: a                                                                                                                                                                                       
Out[37]: [[1], [1], [1], [1], [1]]

In [38]: a = [[] for _ in range(5)]                                                                                                                                                              

In [39]: a[0].append(1)                                                                                                                                                                          

In [40]: a                                                                                                                                                                                       
Out[40]: [[1], [], [], [], []]

#

this is a fairly common gotcha

spice pecan
#

yep

#

But there's barely any difference between doing list_ += iterable and list_.extend(iterable), so just go with whatever feels easier to read in your case

sinful saddle
#

What's the explanation for that last example?

spice pecan
#

multiplication copies the reference to the same list

#

list comprehension evaluates [] every iteration of range, creating new lists

deft pagoda
#

to reiterate, you're seeing the same list 5 times in the first part

spice pecan
#

so in the first example, you have 5 pointers to the same list in another list, and in the second example, you actually have 5 different lists

#

it wouldn't really matter if it were ints, because they're immutable anyway

sinful saddle
#

Okok that's what I thought but I wanted to see if there was anything I was missing.

deft pagoda
#

can make this clear:

In [41]: a = [[]] * 5                                                                                                                                                                            

In [42]: a                                                                                                                                                                                       
Out[42]: [[], [], [], [], []]

In [43]: for i in a: 
    ...:     print(id(i)) 
    ...:                                                                                                                                                                                         
139756415751552
139756415751552
139756415751552
139756415751552
139756415751552

In [44]: a = [[] for _ in range(5)]                                                                                                                                                              

In [45]: for i in a: 
    ...:     print(id(i)) 
    ...:                                                                                                                                                                                         
139756416757632
139756415447424
139756418827136
139756420175040
139756420176000
#

ids are memory addresses --- you can see they're all the same at the top

sinful saddle
#

Both of those are good examples. Thanks for all of the insight!

patent cliff
#

Hey! I had a code-style question since I think I am using some kind of anti-pattern
Following example explains my concern:

try:
    var1: str = obj1.attr1.attr2.attr3
    if not var1:
        raise AttributeError
except AttributeError:
    raise CustomException(f"Uh-oh, got us an exception, Frank!")

In here we try to get the value of attr3, but it is possible that any of obj1, attr1, attr2 are None, hence the try ... except AttributeError
So far so good.
The thing is, attr3 might still be None, and in that case, CustomException should be raised with the same message.
The code above does this without me having to repeat my CustomException. But it feels a little dirty to raise an exception I am explicitly catching.
So the question is: Is the code shared above acceptable, or how would you tackle this specific use-case?

brazen jacinth
#

this is where null conditional operators would be really nice

#

if they existed in python

patent cliff
#

Haha, we have to settle with or 😄

#

Another way to write the code above would be:

if obj1 and obj1.attr1 and obj1.attr1.attr2 and obj1.attr1.attr2.attr3:
    var1: str = obj1.attr1.attr2.attr3
else:
    raise CustomException(f"Uh-oh, got us an exception, Frank!")
#

but this is ugly since you are repeating obj1.attr1 etc

#

So for now I settled for the first approach, but was just wondering if any of you pythonistas had some more elegant way to do this ^^

narrow nexus
#

i have a code how i can fix my issue? python alpha_2 = pycountry.countries.get(alpha_3 = data["country_code"]).alpha_2 print("alpha_2", alpha_2) print("country : ", country) state_name = data["state_code"] print("state_name : ", state_name) subtype = alpha_2+'-'+state_name state_name1 = pycountry.subdivisions.get(code =subtype) print("state_name1 : ", state_name1) state = pycountry.subdivisions.get(code=f'IN-{state_name}') if not state: return jsonify({"message":"Incorrect state code"}),400 print("country_code : ", country_code) try: if alpha_2 == country_code: print("valid state") except Exception as e: print("invalid state") country_match = pycountry.countries.search_fuzzy(country)[0].name.lower()

#

@deft pagoda can u look into my problem here bro?

brazen jacinth
next dirge
#

hello guys !

#

sry for noob question

#

mylst = [9,8,7,6]
mylst.append(35)

brazen jacinth
next dirge
#

alright! duh

cinder plover
#

i have a problem i made a .exe of my file but when i try to send it to someone it says it contains a virus. How can i fix that?

deft pagoda
#

this is not a help channel, please read the topic description

tawny shoal
#

read the message above yours

worn scroll
#

Hello guys, what's the difference betweenclass Stack: stackList = [] and class Stack: def __init__(self): self.stackList = []

charred wagon
#

One is a class attribute and the other is an instance attribute. Instance attributes are scoped only to a specific instance of the object.

worn scroll
#

Thanks

boreal umbra
#

I've done a very terrible thing. I wanted to use the way I had implemented __str__ for a class that I wrote it in such a way that I couldn't make an instance

#

so I did this

#
    new_ann = object.__new__(t.Any)
    new_ann.entities = sorted(new_entities)
    new_ann.relations = sorted(new_relations)

    ann_doc = brat_data.BratFile.__str__(new_ann)
charred wagon
#

A typing.CoroutineFunction or something is really needed. t.Callable[[t.Any], t.Coroutine] is the alias I find myself creating the most.

#

But maybe they don't want to include aliases.

flat gazelle
#

there is already t.Optional

charred wagon
#

Oh, right.

pseudo minnow
#

Hi, mmm... Someone speak spanish? I need help and I'm not so good speaking english. Please send me a message, I need help for a school-homework.

sturdy timber
#

@pseudo minnow This isn't the correct channel for getting help, see #❓|how-to-get-help. This is also an english speaking server so you will have to either try your best or use an online translator. And note there is a limit to how much we can help you with homework, we can guide you in the right direction, but not do it for you of course.

surreal moat
#
    new_ann = object.__new__(t.Any)
    new_ann.entities = sorted(new_entities)
    new_ann.relations = sorted(new_relations)

    ann_doc = brat_data.BratFile.__str__(new_ann)

@boreal umbra could you please explain what you did there? looks intriguing. I see you made an instance of t.Any... but what happened after?

boreal umbra
#

@surreal moat turns out you can't instantiate Any. However my goal was to just create a dummy object that had values for those two attributes, because those are the only attributes needed for BratFile.__str__

surreal moat
#

OH lmao

boreal umbra
#

I ended up doing new_ann = namedtuple('Temp', 'entities relations')(sorted(new_entities), sorted(new_relations)) until I come up with a better solution

surreal moat
#

why don't you use type()?

boreal umbra
#

hmm, that would work

surreal moat
#

type("", (type,), {"entities": sorted(new_entities), "relations": sorted(new_relations)})

boreal umbra
#
    new_ann = type('Temp', (object,), {})()
    new_ann.__dict__ = {'entities': sorted(new_entities), 'relations': sorted(new_relations)}
surreal moat
#

ooh yeah you gotta make the instance first

#

or not?

#

what about just
type("", (type,), {"entities": sorted(new_entities), "relations": sorted(new_relations)}) because it still has the correct attributes

flat gazelle
#

you can do

type('', (), dict(entities=sorted(new_entities), relations=sorted(new_relations)))()
charred wagon
#

Does it bother anyone else that your modules have a lot more in their namespaces than you really want to expose to other modules that import it? For example, everything name module imports can also be seen by other modules. It just seems like clutter. Maybe my way of thinking is a consequence of being used to static analysis in my editor.

flat gazelle
#

thats what __all__ is for

charred wagon
#

That's only for star imports. Does static analysis respect it too?

flat gazelle
#

I would assume so

peak spoke
#

Imports but me a bit, but only thing I care about is what my editor tells me about them, and it ignores modules in trees for representstio etc.

charred wagon
#

I'll try it out

#

PyCharm doesn't care about it at least 😦

peak spoke
#

I've seen some stdlib modules use _ prefixes for import but that feels bit weirder when in that module

outer bronze
#

hello would you help me with a project that I am doing but I am not selling anything I am a beginner

charred wagon
outer bronze
#

:'c

charred wagon
#

I'm coming to the realisation that trying to make things private in modules for the purposes of reducing clutter is a lost cause, since all the imports are still gonna show. I think it only makes sense if some object really shouldn't be used externally.

#

Like, i have a TypeVar. There's no need to ever use it outside the module, but there's no harm either. I could prefix it with _, but there's still 20 other things left that are cluttering the "public" namespace.

#

And a bunch of _-prefixed names are kinda ugly

peak spoke
#

Ive only used "private" names at the top level in modules that had s clear interfaces through one class/function but while it helped on that front they did look a bit ugly as you mentioned

charred wagon
#

What libraries seem to do is use __all__ and then star imports in __init__.py, expecting users to import from the package rather than directly from modules. But I'm not writing a library here.

#

I suppose I'll make an __all__ since it still communicates to readers what's relevant.

paper echo
#

I truly hate star imports