Python Conflicts and File Names

This is my project structure:

a
β”œβ”€β”€ b.py
└── __init__.py
  • The file is b.pyempty.

  • A file __init__.pyis one line:

    b = 'this is a str'
    

Then the following program gives an inconsistent result a.b:

import a
print(a.b)    # str
import a.b
print(a.b)    # module

What is the best way to detect such a name conflict between a variable and a file name?

+4
source share
1 answer

"The next program gives an inconsistent result. print(a.b)"

I would like to point out that, although the results may be different, in fact, Python does nothing contradictory here. Without going into details, this is what happens at every stage of your program.

import a

Python sys.path, : "a.py" "a", __init__.py. Python package. , Python "a" ".py" ( ).

print (a.b)

Python b of a, a __dict__. b 'this is a string', .

import a.b

Python . , b a __dict__, a.b.

print (a.b)

Python b. b - a.b, .

" ?"

script, , ( ) , - . , , ; Python ( - PEP8) - , .

+5

All Articles