Python Identifiers: Rules and Examples

Naming a variable or function in Python means choosing a spelling that the language can read as a name. A Python identifier is the spelling used to name an object or another program element.

This article explains Python’s identifier rules and shows how to check a candidate spelling with str.isidentifier() and keyword.iskeyword().

TL;DR: Python Identifier Rules

A Python identifier is a name in source code, and Python accepts it when it follows identifier syntax and avoids reserved keywords in that context.

  • Names can use Unicode letters and underscores. Digits can follow the first character.
  • Names are case-sensitive and cannot begin with a digit.
  • Use str.isidentifier() for syntax and keyword.iskeyword() for hard keywords.
  • Follow the project style, commonly snake_case for variables and functions.

What Is an Identifier in Python?

An identifier is a spelling used to name an object or program element. In customer_id = 4, customer_id is the identifier and 4 is the integer value.

An assignment, function definition or import can bind a name to an object. Later code uses that spelling to refer to the binding.

A function name such as load_user identifies its action.

Keywords occupy grammar roles. The word for starts a loop clause, while for_item works as an ordinary name. The Python keywords guide covers those reserved words.

Why Identifier Choices Matter

A name shared across modules is part of the interface between them.

For computed values, include a unit suffix when it affects how the number should be interpreted.

  • Distinguish values that coexist in one scope.

How to Check a Python Identifier Step by Step

A candidate name should pass a syntax check before your program stores it or uses it to create an attribute.

Step 1: Choose a candidate spelling

Choose the spelling you want to validate. The checks in the next step distinguish valid identifier syntax from a reserved word.

Step 2: Run the syntax and keyword checks

str.isidentifier() checks the spelling form, while keyword.iskeyword() rejects hard keywords. I ran this file with python3 check_identifiers.py.

import keyword

names = ["customer_id", "2nd_choice", "class", "café", "first-name"]
for name in names:
    valid = name.isidentifier() and not keyword.iskeyword(name)
    print(f"{name}: {valid}")

The command printed these results:

customer_id: True
2nd_choice: False
class: False
café: True
first-name: False
Python identifier checks printed in a terminal

Step 3: Read the result for each name

True means both checks passed. The accented café spelling passes here, while the hyphenated label does not qualify as an identifier.

Python Identifier Edge Cases and Naming Conventions

Unicode letters can appear in Python identifiers, and the parser applies NFKC normalization to their spellings. For shared code, choose spellings the team can read consistently across editors.

Visually similar characters can have different code points. Check the exact spelling when source passes between editors.

Python’s lexical rules set no short universal character cap. External tools can add their own limits, so validate those requirements where data enters the application. A database column, protocol or code generator may impose a separate constraint that Python itself does not know about.

Use distinct unit or stage suffixes when both values occur in the same scope.

  • Use delay_seconds and delay_ms when both units appear in one calculation.
  • Keep raw_payload and parsed_payload distinct when both forms are used.

Uppercase communicates a project’s constant convention, while Python still permits reassignment.

CasePython behaviorPractical choice
First characterLetters and underscores can begin a name. Digits can follow the first character.Start with a descriptive word or underscore.
Caseitem and Item are distinct names.Keep capitalization consistent with the object’s role.
UnicodeMany Unicode letters are accepted.Use spellings that are clear to everyone reading the source.
LengthThe language sets no short universal character limit.Keep names legible and check external system limits.
External labelsStrings can contain punctuation that source identifiers exclude.Map labels deliberately and check for collisions.

Use the project’s casing convention for consistency.

In customer_shipping_address, underscores separate the words and mark their boundaries.

A loop counter used for a few lines can be brief. Treat an exported module name as a public interface.

A suffix such as _seconds or _id communicates meaning to a reader, but spelling alone does not enforce a unit or type. Validate the value at a boundary when an operation depends on that property.

Longer names can help at a public boundary where several fields appear together. Within a short expression, repeated qualifiers can hide the operation, so match the name length to its scope.

RoleCommon formExample
Function or variablelower_case_with_underscorescustomer_id
ClassCapWordsCustomerRecord
ConstantUppercase with underscoresMAX_RETRIES
ModuleShort lowercase namestring_tools
ExceptionCapWords with Error suffixParseError

Python uses established underscore conventions for method parameters and API intent:

  • self and cls name the first parameters of instance and class methods.
  • A leading underscore signals intended internal use.
  • Double-leading names are rewritten with a class-derived prefix to reduce accidental clashes.
  • Double-underscore names such as __init__ identify documented language and library protocols.

Match and case act as soft keywords in the grammar for matching values. Their role depends on their position in the grammar.

The keyword module exposes issoftkeyword() for checking that context-sensitive category on supported Python versions. Keep this separate from the hard-keyword test in the example above.

A dictionary can store “first-name” as a string key. An external label keeps its original spelling even when code maps it to another attribute. The punctuation belongs to the string value, not to a Python variable spelling.

Serializers and API clients may turn field names into object attributes. Keep the conversion rule beside that code and check for collisions.

Input labelPython attributeValidation
first-namefirst_nameKeep the original label and detect duplicate mappings.
account idaccount_idApply one documented conversion rule.

Rebinding list makes that name refer to the new value in its scope. A name such as record_list avoids shadowing the built-in constructor.

See the AskPython guide to Python functions for naming functions in context.

Identifier spelling and name lookup answer different questions. A name can follow the language form while remaining unavailable at the point where code tries to read it.

Scope is the part of a program where a name can be used. A local variable may shadow a name from an outer scope. Inspect the surrounding function when a lookup fails.

Review references before changing an exported spelling.

When validation fails, name the rule the candidate missed. A message such as “start with a letter or underscore” gives the person entering the value a direct correction.

For source files, Python’s parser reports syntax errors. Custom validation belongs at application boundaries, where names come from user input or another system. A validation message should point to the specific rule the input violated.

SituationWhat to checkNext action
Unbound name at a readScope and assignment orderInspect the surrounding function.
Changed public nameCall sites and importsReview compatibility before release.
Generated attributeCollisions and source labelKeep an explicit mapping.

Conclusion: Choose Names Python Can Parse

For exact syntax details, consult the Python language reference linked below.

FAQ

These answers cover common identifier questions that remain after checking a name.

Are Python identifiers case-sensitive?

Yes. Names such as item and Item are distinct identifiers.

Can an identifier start with a number?

No. A digit may appear after the first character, but not at the beginning.

How do I check whether a Python name is valid?

Use str.isidentifier() for identifier syntax and keyword.iskeyword() to reject hard keywords.

Is there a maximum length for a Python identifier?

Python does not set a small fixed maximum identifier length in the language syntax. Keep names readable and check limits imposed by tools or project rules.

Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 259