1

I was reading Python tutorial and came across this line which I couldn't understand:

Standard exception names are built-in identifiers (not reserved keywords).

What is meant by built-in identifiers? I know there are built-in functions like open(),i.e., functions which we don't need to import.

shiva
  • 2,535
  • 2
  • 18
  • 32
  • The standard exceptions are part of the ```builtin```'s their names are just identifiers, NOT keywords. try ```import builtins; for identifier in dir(builtins): print(identifier)```. It should print the name/identifierfor each of the *built-in* Exceptions plus other built-ins. – wwii Jul 14 '16 at 03:41
  • @wwii these are by far not all identifiers python knows, for example `cls` is missing, `__new__`, `__init__` etc. – defoe Jun 21 '19 at 11:05
  • @defoe is `cls` a builtin identifier or a convention that is used as a name for a class object? If you assign a string to the name `cls` will you be shadowing an identifier that Python itself uses? ... [What is the 'cls' variable used for in Python classes?](https://stackoverflow.com/questions/4613000/what-is-the-cls-variable-used-for-in-python-classes) – wwii Jun 21 '19 at 13:43
  • Yes, `cls` does not seem to be a builtin identifier, but `__init__` and `__new__` should be. – defoe Jun 21 '19 at 13:48
  • I just commented [here](https://stackoverflow.com/a/22864250/2823755) wondering about special method names. – wwii Jun 21 '19 at 13:52
  • [2.3.2. Reserved classes of identifiers](https://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers) – wwii Jun 21 '19 at 14:03

4 Answers4

4

It is exactly what you think it is, a name of a thing which isn't a function, and isn't a command like "while", and comes built-in to Python. e.g.

A function is something like open(), a keyword is something like while and an identifier is something like True, or IOError.

More of them:

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 
'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis',
 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 
'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 
'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 
'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 
'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 
'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', 
'_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 
'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 
'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 
'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 
'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 
'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 
'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 
'unicode', 'vars', 'xrange', 'zip']

Documentation backup:

https://docs.python.org/2/reference/expressions.html

5.2. Atoms Atoms are the most basic elements of expressions. The simplest atoms are identifiers or literals

An identifier occurring as an atom is a name

https://docs.python.org/2/reference/lexical_analysis.html#identifiers

Identifiers (also referred to as names)

TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
1

In Python, an identifier is the name given to a particular entity, be it a class, variable, function etc. For example, when I write:

some_variable = 2
try:
    x = 6 / (some_variable - 2)
except ZeroDivisionError:
    x = None

both some_variable and x are identifiers that I have defined. The third identifier here is the ZeroDivisionError exception, which is a built-in identifier (that is, you don't have to import it or define it before you can use it).

This is contrasted with reserved keywords, which don't identify an object, but rather help define the Python language itself. These include import, for, while, try, except, if, else, etc...

Andrew Guy
  • 9,310
  • 3
  • 28
  • 40
1

Identifiers are 'variable names'. Built-ins are, well, built-in objects that come with Python and don't need to be imported. They are associated with identifiers in the same way we can associate 5 with foo by saying foo = 5.

Keywords are special tokens like def. Identifiers cannot be keywords; keywords are 'reserved'.

For built-in keywords like open, though, you can use identifiers with the same spelling. So you can say open = lambda: None and you have overrided or 'shadowed' the built-in previously associated with the name open. It's generally not a good idea to shadow built-ins as it warms readability.

Yatharth Agarwal
  • 4,385
  • 2
  • 24
  • 53
0

You can get all the builtins using following command ...

dir(__builtins__)

it will give following output

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

then if you want to check what can we do with these builtins following will give you the definition help("<name_of_the_builin_function>")

>>> help("zip")
Help on class zip in module builtins:

class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |  
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
caldera.sac
  • 4,918
  • 7
  • 37
  • 69