Python Identifiers

Identifiers are names you give to variables, functions, classes, modules, etc., essentially, names assigned for various components within Python so must adhere to standard nomenclature of language where certain characters reserved and thereby avoided

Rules for Identifiers:

  • Can start with a letter (A-Z, a-z) or underscore(_), cannot begin with number and not include space for this reason or some reserved character/symbol unless overridden by use of the escape sequence mechanism e.g., in strings
  • Can include a mix of upper/lowercase alphanumeric letters, 0-9 and the _ symbol. Special or other reserved names generally to be avoided: they remain valid code as variables but you've introduced unanticipated effects this way so choose accordingly unless intended so deliberately rather than out of need
  • Case-sensitive (myVariable differs from myvariable). Consistent usage simplifies troubleshooting and keeps behaviour as expected once meaning and use settled so prefer whichever better matches surrounding environment whether all lowercase or some mix like camel case
  • Python keywords (reserved words for specialized use within Python like for, while, if, else, def, class, True, False, etc.) cannot be identifiers
    #Valid Identifiers name = "Noorain" _age = 24 student_id = 12345 #Invalid Identifiers 2nd_name = "" # Cannot start with number my variable= "" # Cannot include space

Best Practices:

  • Choose descriptive identifier names reflecting meaning clearly, aids readability (better than `x` for employee record count).
  • Class names generally `CamelCase`. Modules and packages (`lower_case`). Constants typically UPPER_CASE since usually used to define variables outside main method blocks in all-caps
  • Use single/double underscores in method naming: helps specify how exposed methods should appear at level relevant for that usage. Private ones generally remain confined to the particular code block but technically not protected by access-level mechanism restrictions at source like protected or similar for private class definitions
    class MyClass: #Class name using camel case convention def my_public_method(self): # public pass def _my_protected_method(self): #Protected pass def __my_private_method(self): # Private pass