Newby Coder header banner

Python Identifiers

What are identifiers in Python

Identifier is a name given to an object, which is used to access the object

Most things in Python(like class, strings, numbers etc) are objects

For example, in the assignment x = 4, 4 is an object stored in memory and x is the identifier(or name) associated with it

The address (in RAM) of objects can be retrieved through the built-in function id()

x = 4
print('id(x) =', id(x))
print('id(4) =', id(4))

Output

id(x) = 10914592
id(4) = 10914592

Identifiers allow to identify variable, class, function or other objects

Different functions, classes and modules can have the same identifier associated with different objects since they have different namespaces

More about namespaces

Python Identifier rules

Following rules are followed while declaring identifiers in Python

Python is a case-sensitive language, so Var and var are different identifiers

If a variable with a leading underscore (like _xy) is declared in a module(or file) as a global variable and

the module is imported in another module using wildcard (like from module1 import *) then the variable is not imported

Naming Conventions

While the rules are mandatory there are also some conventions related to naming variables, classes or functions like

Check the PEP8 Styling Guide for Python Code for naming conventions and recommendations

Testing and Validation

Python provides methods to check for keywords and identifiers

iskeyword() method

keyword module provides iskeyword() method to check whether a string is a keyword

It can be imported as from keyword import iskeyword

>>>iskeyword('break')
True
>>>iskeyword('Break')
False

isidentifier method

str.isidentifier() function can be used to check if a string is a valid identifier

>>> 'train'.isidentifier()
True
>>> '$train'.isidentifier()
False