Перейти к содержанию

Tips and tricks

The difference between += and =+

i += 1 is the same as i = i + 1, whereas i =+ 1 just means i = (+1).

Augmented assignment statements

Ellipsis or pass?

In Python 3, you can use the Ellipsis literal ... as a «nop» placeholder for code that hasn't been written yet:

def will_do_something():
    ...
But, from the Python documentation:
This object is commonly used by slicing (see Slicings). It supports no special operations. There is exactly one
ellipsis object, named Ellipsis (a built-in name). type(Ellipsis)() produces the Ellipsis singleton.

It is written as Ellipsis or ....

Therefore, for such cases it is better to use pass Statements:

def will_do_something():
    pass

How do I find out which descendant class called the method of the parent class?

Use magic method. For example, like this:

class A:
    def m1(self):
        print(f"The method called the following child class: {self.__class__.__name__}")

class B(A):
    pass

class C(B):
    pass

a = A()
b = B()
c = C()

a.m1()
b.m1()
c.m1()

Output:

The method called the following child class: A
The method called the following child class: B
The method called the following child class: C

Convert CamelCase to snake_case

def camel_to_snake(s):
return ''.join(['_' + c.lower() if c.isupper() else c for c in s]).lstrip('_')

print(camel_to_snake('CamelCaseString'))