Back to series
· 8 min read

Python Identifiers and Keywords


1. What Are Python Identifiers?

An identifier is a name that a programmer defines for the various entities in a program.

In Python, variables, functions, classes, modules, object attributes, and so on can all be named using identifiers.

For example:

name = "Alice"
age = 20

def calculate_total():
    return 100

class User:
    pass

Here:

  • name and age are variable identifiers.
  • calculate_total is a function identifier.
  • User is a class identifier.

The main purpose of identifiers is to provide recognizable names for the objects and program structures in a program.

1.1 The Nature of Identifiers

A variable name in Python is not a memory address that directly stores data in the traditional sense; it is a name-binding mechanism.

For example:

name = "Alice"

This can be understood as:

  • Create or obtain the string object "Alice".
  • Bind the name name to that object.
  • Subsequently access this object through name.

Therefore, an identifier is essentially a name in the program's namespace, not the object itself.

Consider another example:

a = [1, 2, 3]
b = a

b.append(4)

print(a)

Output:

[1, 2, 3, 4]

a and b are two different identifiers, but they are bound to the same list object.

This is also an important foundation for understanding Python variables, object references, and memory management.

2. Python Identifier Naming Rules

Python imposes clear syntactic restrictions on identifiers.

A valid identifier must satisfy the following rules:

  1. It may consist of letters, digits, and underscores.
  2. The first character cannot be a digit.
  3. It cannot contain spaces.
  4. It cannot contain ordinary punctuation marks, such as @, #, -.
  5. It cannot have the same name as a Python keyword.
  6. It is case-sensitive.

2.1 Letters Are Allowed

name = "Alice"
user = "Bob"
total = 100

English letters can be used in identifiers.

2.2 Digits Are Allowed, but Not as the First Character

Valid:

user1 = "Alice"
user2 = "Bob"
version2 = "Python"

Invalid:

1user = "Alice"
2version = "Python"

Digits can appear in identifiers, but cannot be the first character.

2.3 Underscores Are Allowed

_user = "Alice"
user_name = "Bob"
total_price = 100

Underscores are commonly used to:

  • Separate multiple words.
  • Indicate a naming convention for internal use.
  • Construct names with special meanings.

2.4 Spaces Are Not Allowed

Incorrect:

user name = "Alice"

Correct:

user_name = "Alice"

Python does not allow spaces to be included directly inside an identifier.

2.5 Ordinary Special Symbols Are Not Allowed

Incorrect:

user-name = "Alice"
user@name = "Bob"
user#name = "Charlie"

Correct:

user_name = "Alice"
user_name2 = "Bob"

Note that Python's identifier syntax supports Unicode letters, not just ASCII English letters. The use of Chinese and other language characters will be covered later.

2.6 Case Sensitivity

Python is a case-sensitive language.

name = "Alice"
Name = "Bob"
NAME = "Charlie"

print(name)
print(Name)
print(NAME)

Output:

Alice
Bob
Charlie

These three identifiers are independent of one another.

Therefore, when naming, you should keep your casing style consistent to avoid unnecessary confusion.

3. Comparison of Valid and Invalid Identifiers

The following examples will help you quickly grasp the identifier rules.

Identifier Valid? Reason
name Valid Starts with a letter
user_name Valid Uses underscores
user123 Valid Digits appear later
_private Valid Starts with an underscore
UserName Valid Mixed uppercase and lowercase
用户名称 Valid Supports Unicode letters
123user Invalid Starts with a digit
user-name Invalid Contains a hyphen
user name Invalid Contains a space
user@name Invalid Contains a special character
class Invalid Python keyword
for Invalid Python keyword

You can use the keyword module to check whether a string is a keyword, but note: keyword checking is only part of identifier validity checking; other naming rules must also be satisfied.

4. Python Identifiers Support Unicode

Python 3 supports Unicode identifiers.

This means identifiers can use not only English letters but also Chinese, Japanese, Greek letters, and other Unicode letters permitted by the language specification.

For example:

姓名 = "张三"
年龄 = 20

print(姓名)
print(年龄)

Output:

张三
20

Greek letters can also be used:

π = 3.14159
面积 = π * 5 ** 2

4.1 Advantages of Unicode Identifiers

  • Supports multilingual programming.
  • Makes it easy to express business concepts in local languages.
  • Allows the use of letter names corresponding to symbols in mathematical and scientific computing.

4.2 Why Real-World Projects Prefer English Naming

Although Python supports Chinese identifiers, engineering projects generally recommend English naming.

Main reasons:

  • International collaboration is easier.
  • Compatibility with third-party tools and the development ecosystem is better.
  • Code search and maintenance are more consistent.
  • Avoids visual confusion between different characters.
  • Reduces problems caused by encoding, input methods, and team conventions.

For example:

user_name = "张三"
user_age = 20

Compared with:

用户姓名 = "张三"
用户年龄 = 20

English identifiers are generally better suited to long-term team projects.

5. Naming Styles for Python Identifiers

Python not only defines whether identifiers are valid but also establishes a widely adopted set of naming conventions through PEP 8.

Different types of objects usually use different naming styles.

5.1 snake_case: Snake Case

Multiple words are connected with underscores, and all letters are lowercase.

Commonly used for:

  • Variables.
  • Functions.
  • Methods.
  • Modules.
  • Ordinary attributes.

Example:

user_name = "Alice"
total_price = 100
is_active = True

def calculate_total():
    pass

This is the most common naming style in Python.

5.2 PascalCase: Pascal Case

The first letter of each word is capitalized, with no underscores.

Commonly used for class names.

class User:
    pass


class UserService:
    pass


class DatabaseConnection:
    pass

5.3 UPPER_CASE: Uppercase with Underscores

All letters are uppercase, and multiple words are connected with underscores.

Commonly used for constants.

MAX_RETRY_COUNT = 3
DEFAULT_TIMEOUT = 30
API_BASE_URL = "https://api.example.com"

Note that Python does not automatically prevent a variable from being reassigned just because its name is all uppercase.

It is a naming convention that expresses the intent of a constant.

5.4 Mixed Naming Styles

Python also has some special naming forms.

Naming Form Example Common Use
snake_case user_name Variables, functions
PascalCase UserService Classes
UPPER_CASE MAX_SIZE Constants
_name _cache Internal-use convention
name_ class_ Avoid conflicts with keywords
__name __password Name mangling in classes
__name__ __init__ Python special names

5.5 Name Mangling Mechanism

In a class definition, attribute names that begin with two underscores but do not end with two underscores typically trigger name mangling.

For example:

class User:
    def __init__(self):
        self.__password = "secret"


user = User()

print(user._User__password)

Output:

secret

Python mangles __password in the class into a name like _User__password.

Name mangling is mainly used to reduce the chance of accidental conflicts between subclass attributes and parent class attributes; it is not a strict private access control mechanism.

6. What Are Python Keywords

Keywords are special words reserved by the Python language.

These words have specific syntactic meanings and cannot be used as ordinary variable names, function names, or class names.

For example:

if age >= 18:
    print("成年人")

Here:

  • if is a conditional judgment keyword.
  • print is a built-in function name.
  • age is a variable identifier.

The essential differences between keywords and ordinary identifiers are:

  • Keywords are defined by the Python language.
  • Ordinary identifiers are defined by programmers.
  • Keywords have fixed syntactic uses.
  • Ordinary identifiers are used to reference objects or structures in a program.

7. Complete Classification of Python Keywords

Python keywords change as the language version evolves.

The following lists the regular keywords and soft keywords in Python 3.14.

7.1 Regular Keywords

The regular keywords in Python 3.14 include:

False
None
True
and
as
assert
async
await
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield

Regular keywords cannot be used directly as ordinary identifiers.

For example:

class = "User"

This is illegal because class is a keyword.

7.2 Keyword Classification and Usage

Category Keyword Purpose
Boolean values True, False Represent true and false
Null value None Represents a null value
Conditional evaluation if, elif, else Conditional branching
Loop control for, while Loop constructs
Loop jumps break, continue Control loop execution
Logical operations and, or, not Boolean logic
Membership test in Test membership
Identity test is Test object identity
Function definition def, return Define and return from functions
Anonymous functions lambda Define anonymous functions
Class definition class Define a class
Module import import, from, as Import modules
Exception handling try, except, finally Exception handling
Raising exceptions raise Explicitly raise an exception
Assertions assert Debugging and conditional assertions
No-op pass Placeholder statement
Deletion del Delete a name or object reference
Scope global, nonlocal Declare the scope of a name
Context management with Manage resource lifetimes
Generators yield Produce iteration values
Asynchronous programming async, await Define and await asynchronous operations

7.3 Soft Keywords

Besides regular keywords, Python also has soft keywords.

Soft keywords have special meaning only in specific syntactic contexts; in other contexts they can still be used as ordinary identifiers.

The soft keywords in Python 3.14 are:

  • match
  • case
  • _
  • type

For example:

match value:
    case 1:
        print("数字 1")
    case _:
        print("其他值")

Here match and case are used for structural pattern matching.

But in ordinary statements, match can serve as an identifier:

match = "Python"
print(match)

case can likewise be used in ordinary naming contexts.

case = 100
print(case)

The special meaning of a soft keyword depends on the syntactic context; it is not reserved in all situations.

8. Differences Between Regular Keywords and Soft Keywords

This is one of the more confusing points in Python's identifier system.

Comparison Dimension Regular Keywords Soft Keywords
Whether it is a language reserved word Yes Has special meaning in specific syntax
Can it be used as an ordinary variable name No Usually yes
Whether it has context restrictions Usually does not depend on a specific syntactic context Yes
Examples if, for, class match, case, type
How to check keyword.kwlist keyword.softkwlist

You can view the keywords in the current interpreter through Python's standard library keyword module.

import keyword

print(keyword.kwlist)
print(keyword.softkwlist)

Note that the keyword list depends on the Python version currently running.

Do not use keyword lists from other versions to determine the syntax rules of the current interpreter.

9. How to View Python Keywords

Python provides the standard library keyword, used to check keywords and soft keywords.

9.1 View All Regular Keywords

import keyword

for word in keyword.kwlist:
    print(word)

keyword.kwlist returns the list of regular keywords in the current interpreter.

9.2 View All Soft Keywords

import keyword

for word in keyword.softkwlist:
    print(word)

keyword.softkwlist returns the list of soft keywords in the current interpreter.

9.3 Determine Whether a Word Is a Keyword

import keyword

print(keyword.iskeyword("if"))
print(keyword.iskeyword("name"))

Output:

True
False

9.4 Determine Whether It Is a Soft Keyword

import keyword

print(keyword.issoftkeyword("match"))
print(keyword.issoftkeyword("name"))

Output:

True
False

9.5 Write an Identifier Checking Tool

You can combine the string isidentifier() method with the keyword module to write a simple name-checking program.

import keyword


def validate_identifier(name: str) -> bool:
    """Check whether the string can be used as an ordinary identifier."""

    if not name.isidentifier():
        return False

    if keyword.iskeyword(name):
        return False

    return True


names = [
    "user_name",
    "123user",
    "class",
    "User",
    "用户",
    "user-name",
]

for name in names:
    print(name, validate_identifier(name))

Output:

user_name True
123user False
class False
User True
用户 True
user-name False

This check targets ordinary identifiers. Soft keywords still need to be evaluated together with the specific syntactic context.

10. Differences Between Keywords, Identifiers, and Built-in Functions

Beginners often confuse keywords, identifiers, and built-in functions.

They are three different concepts.

10.1 Keywords

Keywords are defined by the Python language and have special syntactic meaning.

For example:

if
for
while
class
def
return

These words cannot be used directly as ordinary identifiers.

10.2 Identifiers

Identifiers are names defined by the programmer.

For example:

name = "Alice"

def greet():
    pass

class User:
    pass

name, greet, and User are all identifiers.

10.3 Built-in Functions

Built-in functions are functions that Python provides in advance and that can be used directly.

For example:

print("Hello")
len([1, 2, 3])
type(100)
sum([1, 2, 3])

print, len, type, and sum are all built-in function names, not Python keywords.

10.4 Comparison of the Three

Comparison Dimension Keyword Identifier Built-in Function
Defined by Python language Programmer Python runtime environment
Whether it has special syntax Yes No No
Whether the name can be redefined Cannot be used as an ordinary name Yes Yes, but not recommended
Example if, for user_name print, len
Lookup method keyword module Syntax rules builtins module

10.5 Why Built-in Functions Should Not Be Overridden

Although Python allows built-in function names to be redefined, this is usually not a good habit.

Not recommended:

list = [1, 2, 3]

print(list)

Here, list no longer refers to the built-in type, but to a list object.

If you later need to create a new list:

numbers = list((4, 5, 6))

An error may occur because list has already been overwritten.

Recommended:

numbers_list = [1, 2, 3]

new_numbers = list((4, 5, 6))

Keeping built-in names from being overwritten is beneficial for code maintenance and understanding.

11. Identifiers and Namespaces

Identifiers do not have to be unique throughout an entire Python program.

Different namespaces can contain the same name.

Python uses namespaces (Namespace) to manage the mapping between names and objects.

11.1 What Is a Namespace

A namespace can be understood as a mapping table from names to objects.

For example:

name = "Alice"

def greet():
    name = "Bob"
    print(name)


greet()
print(name)

Output:

Bob
Alice

Although both variables are named name, they belong to different namespaces.

The name inside the function does not directly overwrite the module-level name.

11.2 Common Namespaces in Python

Common namespaces in Python include:

  • Built-in namespace (Built-in Namespace).
  • Global namespace (Global Namespace).
  • Local namespace (Local Namespace).
  • Attribute namespaces of classes and instances.

11.3 LEGB Name Lookup Rules

When looking up names inside a function, Python generally follows the LEGB rule.

Order Name Meaning
L Local Local scope
E Enclosing Enclosing function scope
G Global Global scope
B Built-in Built-in scope

Name lookup follows the rule of searching level by level from the current local scope outward to enclosing scopes.

For example:

name = "Global"


def outer():
    name = "Enclosing"

    def inner():
        name = "Local"
        print(name)

    inner()


outer()

Output:

Local

Because there is a local variable name inside the inner() function, the local name is used first.