🐍 Python - Variables
Updated at 2017-01-02 23: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.
flip.append(0)
foo()
assert bar == 42
assert flip == [42, 0]
# good, use an object
class Baz:
bar: int = 42
def foo() -> None:
assert Baz.bar == 42
bar = 0
Baz.bar = 8
assert bar == 0
foo()
assert Baz.bar == 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.top + self.height)
# good
class RectangleTwo:
...
def bottom_right(self) -> Tuple[float, float]:
right = self.left + self.width
bottom = self.top + self.height
return (right, bottom)
Sources
- Style Guide For Python Code
- Django Coding Style
- Google Python Guide
- Python Newbie Mistakes
- Learn Python in Y minutes
- Python’s null equivalent: None
- Python Idioms
- Python Best Practice Patterns
- Become More Advanced: Master the 10 Most Common Python Programming Problems
- Python Tricks The Book, Dan Bader
- Fluent Python, Luciano Ramalho