", ...">

Import python classes

Just wondering why

import sys
exit(0)

gives me this error:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in ?
    exit(0)
TypeError: 'str' object is not callable

but

from sys import exit
exit(0)

works great?

+3
source share
3 answers

Python only imports names in the namespace.

Your equivalent first solution should be

sys.exit(0)

because it import sysimports only the keyword sysinto the current namespace.

+8
source

See http://effbot.org/zone/import-confusion.htm for all the different uses importin Python.

import sys

sys "sys" . "exit", sys , :

sys.exit(0)

sys import exit

sys . , "exit" sys.exit.

exit(0)

, , dir.

>>> import sys
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>>
>>> from sys import exit
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'exit', 'sys']

, sys:

>>> dir(sys)
['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
+6

Good from your answers. I can recall that:

import sys from *

will import all elements from sys

0
source

Source: https://habr.com/ru/post/1749006/


All Articles