It is often said that Python has few reserved words. It's not a mistake,
>>> __import__('keyword').kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
As of version 3.3.4, these are 33. But the reserved words are
A lexical element that cannot be used as an identifier even though it meets the rules for a lexical identifier (variable name, function name, class name, etc.) in a programming language.
However, there are a few more "character strings that can be used as identifiers but should not be used".
By the way, it is strictly a lie to say "many Perl reserved words" in the context of "less Python reserved words" (Reference: Is there a reserved word in Perl? --Life is very short //d.hatena.ne.jp/syohex/20110914/1316010018)), there are only a lot of "character strings that can be used as identifiers but should not be used".
A typical example of "a character string that can be used as an identifier but should not be used" is the function name of the built-in function.
>>> list(set([1,2,3,4,3,2,1]))
[1, 2, 3, 4]
>>> list = [1,2,3]
>>> list(set([1,2,3,4,3,2,1]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
If you use it carelessly, there is a risk of overwriting the built-in function. The list of built-in functions is as follows.
>>> 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', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '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']
There are 149! It's probably 72 after abs that you really care about, but it's still over 100 when combined with reserved words. Even if the code doesn't get stuck due to a collision, it's a source of confusion for the reader, so avoid using these in variable names as much as possible.
Variables starting with an underscore (_) have a special meaning in the first place, and it is better to be careful [PEP8 naming rule](https://dl.dropboxusercontent.com/u/555254/ It is written carefully in pep-0008.ja.html#id23), so please refer to it.
here,
Always use self as the first argument of the instance method. Always use cls as the first argument of the class method.
Since something like this is written, self and cls will also be "strings that can be used as identifiers but should not be used (other than for certain purposes)". (Then why these are not reserved words Japanese translation why explicitly write self in Python method arguments -to-stay /) Please refer to
In addition, PEP8 introduces a method of adding one _
like list_
as to how to change the name when it conflicts with the keyword, as in the example of list at the beginning (_ Introduced as how to use
). Do not impair readability by omitting something like lst. I try to improve readability by making it more concrete, such as name_list
.
Recommended Posts