최승호 최승호 - 15 days ago 9
Python Question

Why is _single_leading_underscore function imported?

I found as follow in PEP 8.


_single_leading_underscore: weak "internal use" indicator. E.g. "from M import *" does not import objects whose name starts with an
underscore.


I test this by coding. I make two file. one is "importing_A.py", the other is "A.py". I coded as following.

importing_A.py :

from A import *
a_class = Test()
a_class._single_underscore()


A.py :

class Test:
def _single_underscore(self):
print("executed _single_score()")


and executed "importing_a.py". I expected the result say can't find _single_underscore function, because single underscore function is "weak internal use" indication. However, result is well executed printing "executed _single_score()".

I couldn't know what's wrong. Could you give me any idea?
thank you.

Answer

from A import * imported the class Test. If you had another class ... e.g. _Test, it wouldn't be imported.

Basically, once an object has been imported, all of it's methods/properties are accessible. The leading underscore only prevents top-level objects from being imported (and only when using from module import *).

e.g. with the following a.py:

class Test(object):
    pass

class _Test(object):
    pass

We get:

>>> from a import *
>>> Test
<class 'a.Test'>
>>> _Test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_Test' is not defined
Comments