3

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.

Dave
  • 7,555
  • 8
  • 46
  • 88
Andrius
  • 19,658
  • 37
  • 143
  • 243
  • What do you want to do exactly? Do you want to access the `test_package.STATIC` after you `import test_package`? – Felix Jan 02 '19 at 16:25
  • @feliks yes, in my real case I need to use function that lives inside that module. In example case I want STATIC variable. Idea is su access other attributes than were exposed. As in an example. – Andrius Jan 02 '19 at 16:27

2 Answers2

1

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)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Doesn't seem to work (or am I missing something?). If I do exactly as you described, then I get `NameError: name 'test_package' is not defined`. If I first import `test_package` normally and then try to do your way, then when I try to do `import test_me`, I get `ImportError: No module named 'test_me'` – Andrius Jan 03 '19 at 07:36
  • @Andrius I tested it and it worked for me. Is your test setup *exactly* as you show in the question? Which version of Python are you using? – Mark Ransom Jan 03 '19 at 14:41
  • Well i copy pasted the content, so it should be the same. Python 3 – Andrius Jan 03 '19 at 14:48
  • @Andrius I apologize, when I tested I used a hard-coded path. I didn't realize that `test_package.__path__` is a list and not a string. I've updated the answer. – Mark Ransom Jan 03 '19 at 16:10
0

You need to import them through __init__.py, so change its contents to:

from .test_me import test_me, STATIC

Now the following will work:

import test_package
print(test_package.STATIC)
Felix
  • 1,837
  • 9
  • 26
  • 1
    Well of course it will work. I know that. The question was how to access it if it was not imported. If its even possible? The package is not mine, so I cant just modify it. Or I would need to fork that project and customize it. Which I dont want to do it. – Andrius Jan 02 '19 at 16:36