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 namespacesFollowing rules are followed while declaring identifiers in Python
Identifiers can be a combination of the following characters:
_
) For example var
, identifier1
, test_name
, UpperAndLower
An identifier cannot begin with a number, it should begin with a letter or _
(underscore)
A keyword
cannot be used as an identifier.
Keywords are the reserved words in Python and are used to define the syntax and structure of the Python language, for example if
for
keywords
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 andthe module is imported in another module using wildcard (like
from module1 import *
) then the variable is not imported
While the rules are mandatory there are also some conventions related to naming variables, classes or functions like
_
) _
This is not associated to any Python functionality but is to indicate that they are private variables
Use underscore for joining words in an identifier like
Check the PEP8 Styling Guide for Python Code for naming conventions and recommendations
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