Python import between modules and global variables

I have a question that seems pretty fundamental, but I can't find any help with this.

file_a.py >> from xyz import XYZ class A: . . . file_b.py >> import file_a from file_a import A class B(A): def __init__(self): A.__init__(self) def someMethod(self): XYZ.doSomething() 

XYZ.doSomething () does not work, saying that NameError: the name 'XYZ' is not defined Even a standard import such as "import sys" made from file_a does not seem to make it suitable for use in the_b file. I assumed this should work. I understand what is wrong? If so, is there a way to have common imports and global variables in files? (If this does not help, I was a C ++ and Java programmer, and now I'm starting to use python.)

+6
source share
4 answers

I understand what is wrong?

Yes, since the line from file_a import A only imports the class A into the file_b namespace. The file_a namespace remains valid. If this were not so, there would be little point in having both syntaxes:

 import modulename from modulename import something 

as if your thinking was correct, then after the second form you can always use modulename.someotherthing .

If so, is there a way to have common imports and global variables in files?

Yes, with a star * :

 from modulename import * 

but this leads to a problem of namespace pollution, for example from file_a import * imports into file_b all imports made in file_a . Ultimately, you lose control of your imports and it will bite you at some time ... trust me, what it really is!

If for some reason you need from module import * , a workaround to namespace pollution is to define the __all__ variable in module , which indicates what should be imported using the star operator.

NTN!

+5
source

When importing a module, all variables defined in this module are available in its namespace. Therefore, if XYZ is available in the file_a module, when you import file_a , you can access XYZ as file_a.XYZ .

The general idea here is that your namespace should not be cluttered with the contents of other namespaces.

+4
source

Yes, your understanding is wrong. Each module is its own namespace, and only what you explicitly import into this file is available in this namespace.

Unlike other answers, not particularly Pythonic refers to file_a.XYZ , although this will work. Instead, you should import XYZ and sys at the top of file_b .

+3
source
 import file_a from file_a import A 

I think the problem is that you really do not import XYZ!

 from fila_a import * 

may solve your problem, but this is not a good way ~~~

you can write this in the_b file:

 from file_a import XYZ 

It's done?

+1
source

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


All Articles