General Python Tips

language features

x = y = 18
print(id(x),id(y), id(18))
x is y
140711489444032 140711489444032 140711489444032
True
chr(int('0x10FFFF',base=16))#.to_bytes(3, 'big')
'\U0010ffff'

back to top

class decorators

Works as a hidden inheritence

def decorator(cls):
    class wrapperClass(cls):
        attribute = "value"
    return wrapperClass

@decorator
class exampleClass:
    ...

example = exampleClass()
example.attribute
'value'
example.__class__
__main__.decorator.<locals>.wrapperClass

back to top

metaclass

Something like a factory. Ultimately, type creates the objects, apparently.

class Meta(type):
    def __new__(mcs, name, bases, class_dict, **kwargs):
        class_ = super().__new__(mcs, name, bases, class_dict)
        if kwargs:
            for name, value in kwargs.items():
                setattr(class_, name, value)
        return class_

class testMeta(object, metaclass=Meta, attr1=True, attr2='42'):
    def __init__(self, name, value):
        self.name = name
        self.value = value
        
dir(testMeta(" ",10))[-4:]
['attr1', 'attr2', 'name', 'value']

back to top

dict

proper dictionary manipulation

Accessing with default value.

d = {'a':1, 'b':2, 'c':3}

d.get('d',0)
0

Using KeyError to set new keys.

try:
    print(f"{d['d']= }")
except KeyError:
    d['d']=0
d['d']
0

Since python 3.9 the union operator | works in dicts as well. Since I am currently on 3.8, here’s a union of sets, but you get the gist.

{1,2,3} | {4,5}
{1, 2, 3, 4, 5}

back to top

Printing

It is possible to append :character[<^>]number while formatting a string to include a character multiple times so as to the final string have size of at least number

print("{:_^24}".format("lero"))
"{:_>14}".format("lero")
__________lero__________
'__________lero'

f-strings can be formatted to insert variables/expressions before equal sign and value.

d = {'a':1, 'b':2}
f"{d['b']= }"
"d['b']= 2"

back to top