Alo
Alo

Alo

Python: Variables

Photo by Jack Anstey on Unsplash

Python: Variables

Alo's photo
Alo
ยทApr 9, 2022ยท

2 min read

Rules ๐Ÿ“

You can name a variable any name as long as it follows these rules:

  1. it can be only on word
  2. it can only use letters, numbers and the underscore character
  3. it can't start with a number
# DO
correct_variable_name_1 = "Hello"


# DON'T
incorrect variable = "Can be only one word."
&-incorrect#@variable = "Can only use letters, numbers and the underscore character"
123_incorrect_variable = "Can't start with a number."

Bonus: underscore in Python ๐ŸŒŸ

PEP 8 define a few rules around using underscore in variable names.

Name starting with an underscore: Weak internal use

Variables starting with _ are considered unuseful , internal or private.

When importing automatically everything from a module (from MODULE import *), variables starting with an _ won't get automatically imported.


# example.py
_secret = "I am secret!"
public = "I am public"

# main.py
from test import *  

print(public)  
print(_secret)
# >> ๐Ÿ”ด NameError: name '_secret' is not defined

However, this is weak as nothing stops you from forcing the import of the variable.


# example.py
_secret = "I am secret!"
public = "I am public"

# main.py
from test import _secret  

print(_secret)

# >> "I am secret!"

Name ending with an underscore: Avoid conflicts

A variable name might end with an underscore to avoid conflicts with Python keywords.

# we use `class_` to avoid conflict with Python's class declaration keyword
class_ = "ClassName"

Name starting with two underscores: Name mangling

Using two underscores when naming a class attribute invokes name mangling.

For example, inside the class Cat, the attribute __name can be accessed with _Cat__name.

class Cat:  

    def __init__(self, name):  
        self.__name = name  

cat = Cat("Felix")  

print(cat.__name)
# >> ๐Ÿ”ด AttributeError: 'Cat' object has no attribute '__name'

print(cat._Cat__name)
# >> Felix

Why use name-mangling?

Python doesn't have the concept of private/public attributes in class. Name mangling is a way to make the attribute somewhat more private.

However, a user could still access the variable by calling its mangled name (cat._Cat__name in our example).

Name starting with two underscores and ending with two underscores: Magic attributes and object

Naming a variable with two underscores at the front and two underscores at the end indicates a magic attribute or object.

For example, __init__ is a magic attribute of a class that is called when an instance is created. In other words, __init__ defines our constructor.

ย 
Share this