🐍 Python

Updated at 2017-01-03 01:22

Python variables are just references to Python objects. Variables are not identity, type or value, they are just labels.

Every Python object has an identity, a type and a value. But only the value can change during the lifetime of an object.

Data attributes and methods are collective known as attributes in Python. Methods are just attributes that are callable. Public data attributes can be wrapped to properties with accessor methods (get/set).

Avoid global variables. Fetching global variables is slow, they pollute the runtime environment and will cause hard to debug problems.

# bad
from typing import List

bar: int = 42
flip: List[int] = [42]

def foo() -> None:
    # You could use global bar here to access the global, but avoid.

    # Does not change global, creates new local variable.
    bar = 0

    # Changes global as no assignment is done.

assert bar == 42
assert flip == [42, 0]
# good, use an object
class Baz:
    bar: int = 42

def foo() -> None:
    assert == 42
    bar = 0 = 8
    assert bar == 0

assert == 8

Use multiple assignment to swap variables. It is faster, especially if done in a loop.

x: int = 10
y: int = 20

# bad
temp: int = x
x = y
y = temp

# good
x, y = y, x

Use temporary variables for readability.

from typing import Tuple

# bad
class RectangleOne:

    def bottom_right(self) -> Tuple[float, float]:
        return (self.left + self.width, + self.height)

# good
class RectangleTwo:

    def bottom_right(self) -> Tuple[float, float]:
        right = self.left + self.width
        bottom = + self.height
        return (right, bottom)