4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonのprintに値を代入すると...

Last updated at Posted at 2019-03-13

Introduction

Python2系とPython3系で異なる挙動を示したのでメモしておきます。

Python2系で print = としてみる

Python2系で以下のように実行してみます。

>>> print = 1

すると

  File "<stdin>", line 1
    print = 1
          ^
SyntaxError: invalid syntax

これはPython2系ではprintが予約語として存在しているためです

Python3系で print = としてみる

次にPython3系で以下のように実行してみます。

>>> print = 1

するとエラーもなく、printという変数に値が代入されてしまいました。この状態でprint関数を使ってみましょう。

>>> print('hogehoge')

すると以下のようなエラーが返ってきます。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

intオブジェクトは上述のように呼び出せるものではありませんと怒られてしまいます。これは元々あったprint関数が値によって上書きされ、関数ではなくなってしまったためです

予約語でないため例外が発生しない、とはいえこれは注意したいポイントです。

追記: Python3系での標準関数復活方法

@shiracamus様より元に戻す方法を伝授していただきました。ありがとうございます。

Python3系での標準関数復活方法

もしprint = 1のようにPythonの標準関数に値を代入してしまった場合、以下の方法を用いて元に戻すことができます。

__builtins__を用いて元に戻す

>>> print = __builtins__.print
>>> print('hogehoge')
hogehoge

これはPythonの標準関数が__builtins__の中にあるためです。試しに、あるモジュール内で定義されている名前を調べることができる、dir関数を引数なしで呼び出してみましょう。

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

次に__builtins__の中を見てみます。すると組込み関数や変数の名前を列挙することができます。

>>> 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', 'ModuleNotFoundError', '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', 'breakpoint', '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']

__builtins__内にprintが定義されていることがわかります。

del文を用いて元に戻す

代入で戻さずに、ローカルで代入したprint変数を削除することでも戻すことも可能です。

>>> print = 1
>>> print('hogehoge')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del print
>>> print('hogehoge')
hogehoge

これはローカルにprintという名前がない場合は、Pythonが__builtins__の中を探し行く仕様になっているためです。

4
4
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?