2

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.

Mr.choi
  • 501
  • 2
  • 5
  • 17
  • 1
    Methods on objects aren't imported, types (and functions) are. The standard visibility rules for methods apply. You could use two underscores to name mangle the method but that would just make it harder to call. – Voo Nov 20 '16 at 02:40

1 Answers1

3

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
mgilson
  • 300,191
  • 65
  • 633
  • 696