SoFunction
Updated on 2025-04-13

Python naming specifications and best practices

1. Specifications

1. Variable names are case sensitive;

2. It is strictly forbidden to use keywords as variable names;

3. Determine your naming style and do not change it at will;

4. The naming should be scientific and rigorous, and should not be too long or the expression is vague;

5. If special conventions or abbreviations are used in the naming, there must be commentary instructions;

6. Try not to use Chinese characters and pure mathematical characters to avoid encoding errors;

7. Names are composed of English letters, numbers, and underscores, such as abc, abc13 and _abc, etc.;

8. Be clear and clear, have clear meanings, and use complete words or abbreviations that everyone can basically understand;

9. In the same software product, the naming of interface parts (variables, structures, functions and constants) should be planned to prevent conflicts during compilation and linking.

2. Reference

type Public/external members Private/internal membership
module my_naming_convention _my_naming_convention
Package my_naming_convention
Class MyNamingConvention _MyNamingConvention
Exception MyNamingConvention
Function my_naming_convention() _my_naming_convention()
Global/class constants (constant) MY_NAMING_CONVENTION _MY_NAMING_CONVENTION
Global/class variables (variable) my_naming_convention _my_naming_convention

3. Abbreviation

When naming, you should try to use fully spelled words. There are two types of abbreviation:

  • Commonly used abbreviations, such as XML, ID, etc., should only have capital letters when naming, such as XmlParser.

  • The name contains long words, which abbreviates a certain word. At this time, the abbreviation method that is agreed upon is customary should be used.

For example:

function abbreviation fn

text abbreviation txt

object abbreviation obj

count abbreviation cnt

number abbreviation num

4. Underline the leading suffix

  • A leading underscore: means non-public ownership.
  • A suffix underscore: Avoid keyword conflicts.
  • Two leading underscores: used when naming a class attribute causes a name conflict.
  • Two leading and suffix underscores: "magic" (with special use images) objects or attributes, such as __init__ or __file__. Never create names like this, just use them.

Note: There is some controversy over the use of underscores.

5. Names that should be avoided

  • Single letter names, except counters and iterators.
  • Hyphen in package/module name (-)
  • Names that start and end with double underscores (Python reserved, for example __init__)

This is the end of this article about Python naming specifications and best practices. For more related Python naming specifications, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!