1

When we use from <module/package> import *, none of the names that start with a _ will be imported unless the module’s/package’s __all__ list explicitly contains them.

Is this not applicable to variables and functions of a class?

From the below programs, it seems it's not applicable to variables and function inside a class.

_bar and _check_func both are executed in test_import.py. However, _test_func() throws an error for having leading underscore. Am I missing anything here?

test_var.py

class test:
    def __init__(self):
        self._bar=15
    def test_mod(self):
        print("this is test mod function")
    def _check_func(self):
        print("this is _check_func function")

def _test_func():
    print("this is test function var 2")

test_import.py

from test_var import *

p1=test()
print(p1._bar)
p1.test_mod()
p1._check_func()

_test_func()

Output:

15
this is test mod function
this is _check_func function
Traceback (most recent call last):
  File "test_import.py", line 8, in <module>
    _test_func()
NameError: name '_test_func' is not defined
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
nl09
  • 93
  • 1
  • 9
  • 2
    By convention class members with a single underscore at the front are to be treated as the equivalent of private members in other languages and are not to be used by code outside the class. However this is not imposed by the language, but in any case wise programmers obey the convention. – Paula Thomas May 26 '18 at 16:20
  • the first answer have nice expclication https://stackoverflow.com/questions/8689964/why-do-some-functions-have-underscores-before-and-after-the-function-name – Druta Ruslan May 26 '18 at 16:24
  • That makes sense. Since class members with leading underscore need to be treated as private members, it should not be used outside of the class. Thanks – nl09 May 27 '18 at 09:58

2 Answers2

0

The underscore rule is imposed by the importer when it sees from test_var import *. In fact, the functions are still in the module namespace and you can still use them:

import test_var
test_var._test_func()

You don't import class methods, just classes so the underscore rule isn't applied. p1._check_func() works for the same reason that test_var._test_func() works: You addressed the variable in its namespace.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

You imported test and are accessing its members (with or without underscores) through that namespace (in your example, through the instantiated object p1). test is what you import, test._bar is only accessible through test and is not among the imported symbols.

tripleee
  • 175,061
  • 34
  • 275
  • 318