Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - access module from package that is not imported through __init__.py?

I'm using one package that with __init__.py import only one variable from module, but whole module itself is not exposed. Is there a way to access that module?

Lets look in this case:

Whole package:

test_package/
├── __init__.py
└── test_me.py

Now contents:

__init__.py:

from .test_me import test_me

test_me.py:

STATIC = 'static'


class Test:
    pass


test_me = Test()

Now if I import package test_package. I can only access variable test_me, which is an instance of Test class. Though I can't access STATIC variable, because module itself was not exposed.

Is there a way to access test_me module in this case and not only one of its variables?

P.S. If I use sys to append path directly to that package's module, it throws error that such module does not exist when I try to import it.

like image 274
Andrius Avatar asked Dec 01 '25 21:12

Andrius


1 Answers

If you add the package directory to your path, Python can import any file in that directory as if it were a module by itself.

import sys
sys.path.extend(test_package.__path__)
import test_me
print(test_me.STATIC)
like image 56
Mark Ransom Avatar answered Dec 03 '25 12:12

Mark Ransom