Using modules imported from another import

I am cleaning up a project that has been reorganized into smaller .py files. I noticed that many modules are imported over and over into various files. Some statements are in files that import another, which has the same import statement that is used by the importing file. For instance:

main.py

import alt
print (os.getcwd())

alt.py

import os

print(os.getcwd())throws out a NameError: name 'os' is not defined. Shouldn't osbe part sys.moduleswhen the import statement is executed in alt.py?

Can I use a module imported by another module that was first imported?

+4
source share
4 answers

They are available in the following namespace:

import alt
print (alt.os.getcwd())
+5
source

os alt. os , alt.os. , alt from alt import *, , ...

, , . , main.py:

 import os

+1

, , .

, . , alt os, main

print(alt.os.getcwd())

, , os . import os main. , .

, , sys.modules, . sys.modules .

import alt , sys.modules['alt'], alt main. import os alt . , sys.modules['os'] alt.os. import alt import os main, . os , sys.modules['os'].

main getcwd:

  • ():

    import alt
    import os
    print(os.getcwd())
    
  • alt ( /):

    import alt
    print(alt.os.getcwd())
    
  • sys.modules ( , , ):

    import alt  # necessary to trigger the actual import
    import sys
    print(sys.modules['os'].getcwd())
    

All imports download the complete module. This also applies to importing a form from os import getcwd. The module sys.modules['os']is still being created. The only difference is that the import namespace will only have access to the name getcwd, not os. In your case, if it altcontains from os import getcwdinstead import os, the three access methods will change as follows:

  • Without changes.
  • print(alt.getcwd())since it alt.osno longer exists.
  • Without changes.
0
source

You write it like this

__author__ = 'kerberos'
__date__ = '2017/10/25 20:48 '
import alt
print(alt.os.getcwd())

This is the result:

C: \ Users \ Administrator \ Desktop \ 11

-1
source

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


All Articles