PythonIntroduction to PythonPython fundamentals
What are identifiers in Python?
Question 18 of 20 · Updated
On this page
- 1. Where are identifiers used?
- 2. Rules for writing Python identifiers
- 3. Are identifiers case-sensitive?
- 4. How do you check whether a Python identifier is valid?
- 5. Can Python identifiers contain Unicode characters?
- Unicode normalisation and confusingly similar names
- 6. Identifiers, names and objects
- 7. How do identifiers relate to scope?
- 8. What is the difference between identifiers, keywords and built-in names?
- 9. Recommended naming conventions
- 10. Common identifier errors
- 11. Practical example: validate names for an ASCII-only naming policy
- 12. Frequently asked questions
- Can an identifier start with a number?
- Is an underscore a valid identifier?
- Is self a reserved keyword?
- Can a Python identifier contain spaces or hyphens?
- Is there a fixed maximum identifier length?
- Are identifiers the same as variables?
- 13. Interview-ready answer
- Key takeaways
- Official references
An identifier in Python is a name used in source code to identify a named entity, such as a variable, function, class, parameter, module or attribute. Identifiers make it possible to refer to objects and organise program logic using meaningful names.
Python has rules that determine whether a spelling is a valid identifier. These rules are part of the language grammar. Naming conventions, such as using snake_case for functions, are separate recommendations for making code easier to read.
For example:
PYTHONprice = 120 quantity = 3 def calculate_total(price, quantity): return price * quantity print(calculate_total(price, quantity))
Output:
360The names price, quantity and calculate_total are identifiers. The function parameters are also identifiers. The words def and return are reserved keywords, while 120 and 3 are integer literals.
1. Where are identifiers used?#
Identifiers appear throughout a Python program.
| Named entity | Example identifier | Purpose |
|---|---|---|
| Variable | total_price | Refer to a value through a name binding |
| Function | calculate_total | Refer to a callable defined by the program |
| Parameter | quantity | Refer to an argument received by a function |
| Class | ShoppingCart | Name a class definition |
| Attribute | balance | Identify an attribute of an object, as in account.balance |
| Imported name | math | Refer to an imported module or object |
| Exception alias | exc | Refer to an exception in an except clause |
The same spelling can appear in different namespaces and refer to different objects. For example, two unrelated functions can each have a local variable named result without sharing that variable.
An identifier is not itself a data type. It is a source-code name; the object associated with that name can have a type such as int, str, list or a user-defined class.
2. Rules for writing Python identifiers#
For ordinary ASCII identifiers, these rules are sufficient:
- Start with a letter (A–Z or a–z) or an underscore.
- After the first character, use letters, digits or underscores.
- Do not use spaces, hyphens or ordinary punctuation inside the name.
- Do not use a reserved Python keyword as an ordinary identifier.
- Remember that names are case-sensitive.
Python 3 also accepts many Unicode characters according to the language's Unicode identifier rules. Consequently, the ASCII rules are a useful beginner-friendly subset rather than the complete grammar.
Examples:
| Name | Valid ordinary identifier? | Explanation |
|---|---|---|
| customer_id | Yes | Letters and an underscore |
| _count | Yes | Starts with an underscore |
| item2 | Yes | A digit occurs after the first character |
| MAX_RETRIES | Yes | Uppercase letters and an underscore |
| 2items | No | Starts with an ASCII digit |
| first-name | No | A hyphen is not permitted inside an identifier |
| first name | No | Contains a space |
| total$ | No | Contains a dollar sign |
| class | No | Reserved keyword |
| match | Yes, outside its special grammar context | A soft keyword in Python 3.10 and later |
| café | Yes | Contains permitted Unicode letters |
The spelling Class is not the reserved keyword class, but changing capitalization solely to avoid a keyword is rarely the clearest naming choice.
3. Are identifiers case-sensitive?#
Yes. Python distinguishes uppercase and lowercase letters in identifiers.
PYTHONtotal = 10 Total = 20 print(total, Total)
Output:
10 20These assignments create two distinct name bindings. A spelling such as TOTAL would be another distinct name.
In application code, avoid creating names that differ only in capitalization unless the distinction is clear and follows a recognised convention. For example, a class named Invoice and an instance named invoice can be appropriate, whereas total and Total as competing ordinary variables are easy to confuse.
4. How do you check whether a Python identifier is valid?#
Python provides two particularly useful checks:
- str.isidentifier() checks whether the string has a valid lexical identifier form.
- keyword.iskeyword() checks whether the string is a reserved keyword in the running interpreter.
The following example demonstrates both:
PYTHONimport keyword names = ["user_id", "_count", "item2", "2items", "first-name", "class", "match", "café", "变量"] for name in names: print(name, name.isidentifier(), keyword.iskeyword(name))
Output on Python 3.13.5:
user_id True False
_count True False
item2 True False
2items False False
first-name False False
class True True
match True False
café True False
变量 True FalseThe result for class is important. isidentifier() returns True because the spelling has the right lexical form, but iskeyword() also returns True because class is reserved.
For an ordinary name, check both conditions: the spelling must satisfy isidentifier(), and it must not be a reserved keyword.
This is a lexical check, not a guarantee that a name can be used in every context. Soft keywords, scope declarations, special grammar positions, Unicode normalisation and name collisions can introduce additional constraints. For generated Python code, validate against the intended Python version and the actual grammatical context.
The earlier Python keywords lesson discusses reserved words and soft keywords in greater detail.
5. Can Python identifiers contain Unicode characters?#
Yes. Python 3 supports non-ASCII identifiers using Unicode character properties. The language reference defines the exact rules in terms of identifier-start and identifier-continue character sets, derived from Unicode XID_Start and XID_Continue properties, with the underscore allowed at the start.
PYTHONcafé = 5 变量 = 7 print(café + 变量)
Output:
12Not every Unicode character is valid in a name. For example, most emoji are not valid identifier characters. Nor is every character that looks like a letter necessarily permitted.
Use the interpreter's isidentifier() method rather than an oversimplified regular expression when you need to accept Python's complete lexical identifier set.
Many teams nevertheless prefer ASCII identifiers for shared application code because they simplify typing, search, code review and communication across different keyboard layouts. This is a project convention, not a general prohibition on Unicode identifiers.
Unicode normalisation and confusingly similar names#
Python normalises identifiers to Unicode Normalization Form KC (NFKC) while parsing source code. Consequently, visually different source spellings can denote the same name.
PYTHONimport unicodedata K = 1 K = 2 print(K) print(unicodedata.normalize("NFKC", "K"))
Output:
2
KThe second assignment uses U+212A, the Kelvin sign. NFKC normalises it to the ordinary uppercase K, so both assignments refer to the same binding.
The opposite problem also exists: characters from different writing systems can look similar without normalising to the same name. For security-sensitive or generated code, consider an explicitly documented naming policy and check normalised names for collisions.
This normalisation occurs for identifiers in parsed Python source. Arbitrary string values, including dictionary keys and strings passed to getattr(), are not automatically subject to the same source-code identifier normalisation.
6. Identifiers, names and objects#
A common beginner misconception is that the identifier itself contains an object. Python instead associates names with objects through bindings.
PYTHONitems = [1, 2] backup = items backup.append(3) print(items) print(items is backup)
Output:
[1, 2, 3]
TrueThere are two identifiers, items and backup, but both names refer to the same list. Mutating the list through backup changes the object seen through items as well.
Conceptually:
items ----+
+----> [1, 2, 3]
backup ----+Reassigning backup to another list would change that name's binding; it would not automatically reassign items.
This distinction between names and objects is important when working with mutable collections, function arguments and object references.
7. How do identifiers relate to scope?#
A name is interpreted within a particular scope. Python uses its name-resolution rules to determine which binding an expression refers to.
PYTHONvalue = 100 def display(): value = 20 print(value) display() print(value)
Output:
20
100The assignment within display creates a local binding named value. The module-level value remains unchanged.
The same identifier spelling can therefore refer to different objects depending on its context. This is not a syntax error or a naming-rule violation.
Scope, namespaces, global and nonlocal declarations, closures and name resolution have their own detailed rules. Here the important point is that a valid identifier's meaning depends on its binding and the context in which it is evaluated.
8. What is the difference between identifiers, keywords and built-in names?#
| Concept | Meaning | Examples |
|---|---|---|
| Identifier | A name used in source code | customer_id, Invoice |
| Reserved keyword | A spelling reserved by the language grammar | def, class, return |
| Soft keyword | A spelling with a special role in specific grammatical contexts | match, case, type |
| Built-in name | A name provided by Python's builtins namespace | len, print, list |
| Literal | Source notation for a value | 42, "hello" |
Built-in names are not generally reserved keywords. Python permits shadowing a built-in name, but doing so can make a program difficult to understand.
PYTHONimport builtins list = "not a list" print(builtins.list((1, 2)))
Output:
[1, 2]The name list now refers to a string in the current module. The explicit builtins.list reference still accesses the built-in list type.
In real code, choose a name such as values or items instead of shadowing list. Accessing builtins explicitly is useful for demonstrating what happened, but it is not a substitute for good naming.
A string key such as "class" in a dictionary is also valid: the string is data, not an ordinary source-code identifier.
9. Recommended naming conventions#
Python's naming rules describe what the language permits. PEP 8 describes common conventions for what developers should prefer.
| Kind of name | Typical convention | Example |
|---|---|---|
| Variable | snake_case | customer_name |
| Function or method | snake_case | calculate_tax |
| Class | CapWords | PaymentService |
| Constant | UPPER_CASE | MAX_CONNECTIONS |
| Module | short lowercase name | invoice_utils |
| Non-public interface | leading underscore | _cache |
Choose names that reveal purpose. elapsed_seconds is more informative than t when the unit matters; customer_id is clearer than x in a function that looks up a customer.
Names with special underscore patterns require care. A single leading underscore commonly indicates a non-public interface. Double leading underscores in a class can trigger name mangling under the applicable rules. Names such as __init__ have documented special meanings. These conventions do not provide access-control security.
For more detailed style guidance, see the PEP 8 lesson. Naming conventions should not be applied mechanically in a way that breaks a public API or changes behaviour.
10. Common identifier errors#
The following example demonstrates invalid source code without preventing the demonstration itself from running.
PYTHONfor source in ["class = 1", "2items = 1", "first-name = 1"]: try: compile(source, "<example>", "exec") except SyntaxError: print("Invalid:", source) try: print(unknown_name) except NameError: print("Valid spelling, missing binding")
Output:
Invalid: class = 1
Invalid: 2items = 1
Invalid: first-name = 1
Valid spelling, missing bindingThere are two distinct situations:
- SyntaxError: The source is not valid in its grammatical context. A reserved keyword cannot be used as a normal assignment target, and a hyphenated expression is not a valid single identifier.
- NameError: The name has a valid spelling, but evaluation cannot find a corresponding binding in the applicable namespaces. UnboundLocalError is a specialised subclass of NameError for certain local-name failures.
The demonstration compiles fixed instructional strings but does not execute them. Never evaluate untrusted source text merely to check whether its names are valid.
Other common mistakes include misspelling names, using inconsistent capitalization, accidentally shadowing built-ins and creating identifiers that are valid but too vague to communicate their purpose.
11. Practical example: validate names for an ASCII-only naming policy#
Suppose a project needs field names that can also be ordinary ASCII Python identifiers. The following validator combines a project-level ASCII restriction with Python's lexical and reserved-keyword checks.
PYTHONimport keyword def valid_ascii_name(name): return (name.isascii() and name.isidentifier() and not keyword.iskeyword(name)) for name in ["customer_id", "class", "first-name", "café"]: print(name, valid_ascii_name(name))
Output:
customer_id True
class False
first-name False
café FalseThis example deliberately rejects café even though it is a valid Python identifier. The restriction belongs to the hypothetical application's naming policy.
A real schema-to-code generator should additionally:
- Ensure that generated names are unique after any normalisation or sanitisation.
- Account for the target Python version and syntactic context.
- Preserve a mapping between external field names and generated identifiers.
- Avoid clashes with existing names and protected application interfaces.
- Use a structured code-generation approach instead of executing arbitrary user input.
For a name of length n, checking its lexical form requires O(n) time in the usual character-scanning model. The simple validator requires no additional collection proportional to n. Validating an entire schema may require additional memory to track previously assigned names.
12. Frequently asked questions#
Can an identifier start with a number?#
An ASCII digit cannot begin an ordinary Python identifier. A digit can occur after an allowed initial character, as in item2.
Is an underscore a valid identifier?#
Yes. A single underscore is an ordinary identifier in many contexts. In structural pattern matching it has a special wildcard role in an appropriate pattern. Some interactive environments also use it to hold a previous result.
Is self a reserved keyword?#
No. self is an ordinary identifier conventionally used for the first parameter of instance methods.
Can a Python identifier contain spaces or hyphens?#
No. Use underscores to separate words in an ordinary multiword identifier.
Is there a fixed maximum identifier length?#
The Python language does not specify a small fixed maximum identifier length. Practical implementation and resource limits still exist. Prefer concise, descriptive names rather than extremely long identifiers.
Are identifiers the same as variables?#
No. A variable name is one use of an identifier. Function names, class names, parameters and many attribute names are also identifiers.
13. Interview-ready answer#
Identifiers in Python are names used to identify variables, functions, classes, parameters and other named entities. Ordinary ASCII identifiers must begin with a letter or underscore and may then contain letters, digits and underscores. Python 3 also supports permitted Unicode characters. Identifiers are case-sensitive, and reserved keywords cannot be used as ordinary names. Use str.isidentifier() together with keyword.iskeyword() to check a candidate's lexical eligibility. Valid names should also follow suitable naming conventions, avoid shadowing built-ins and be meaningful in their scope.
Key takeaways#
- An identifier is a name, not the object itself.
- Python supports ASCII and permitted Unicode identifiers.
- Reserved keywords and invalid lexical spellings are different reasons to reject a name.
- Python normalises Unicode identifiers in source code using NFKC.
- Naming conventions promote readability but are distinct from grammar.
- Validating a name alone does not make generated code safe.
Official references#
- Python 3.13 Language Reference — Names (identifiers and keywords)
- Python Standard Library — str.isidentifier
- Python Standard Library — keyword
- PEP 3131 — Supporting Non-ASCII Identifiers
- PEP 8 — Style Guide for Python Code
- Python Language Reference — Execution model
Verification note: All ten standalone Python examples were executed locally on Python 3.13.5 and their outputs were checked. Official reference links are provided using established knowledge under the authorised offline research exception; live documentation was not checked.
References
- 1.
- 2.Python Standard Library — str.isidentifierdocs.python.org
- 3.Python Standard Library — keyworddocs.python.org
- 4.PEP 3131 — Supporting Non-ASCII Identifierspeps.python.org
- 5.PEP 8 — Style Guide for Python Codepeps.python.org
- 6.Python Language Reference — Execution modeldocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design