Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import private methods in Python?

Tags:

python

def __hello_world(*args, **kwargs):
  .....

and I tried

from myfile import __helloworld

I can import the non private one.

How do I import private methods?

Thanks.


I am now using a single underscore.

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    from myfile.ext import _hello_world
ImportError: cannot import name _hello_world

in my test.py

sys.path.insert(0, os.path.abspath(
                    os.path.join(
                        os.path.dirname(__file__), os.path.pardir)))

from myfile.ext import _hello_world
like image 462
User007 Avatar asked Dec 21 '22 22:12

User007


2 Answers

$ cat foo.py
def __bar():
    pass

$ cat bar.py
from foo import __bar

print repr(__bar)

$ python bar.py
<function __bar at 0x14cf6e0>

Perhaps you made a typo?

However, normally double-underscore methods aren't really necessary - typically "public" APIs are zero-underscores, and "private" APIs are single-underscores.

like image 124
Amber Avatar answered Dec 23 '22 12:12

Amber


Are you sure you have the latest source imported? Double check that you are importing the latest source.

check it by doing this:

>> import myfile.ext
>> print dir(myfile.ext)

You should see all the methods (I think double underscore will be skipped, but single will still appear). If not, it means you have an old version.

If this shows okay, but you still can't import the actual thing. Make a virtualenv, and try again.

like image 33
CppLearner Avatar answered Dec 23 '22 12:12

CppLearner