10

I'm trying to import a function which is in a module inside a package in Python, but when I try:

from package.module import some_function

Python executes the package's __init__.py but it can't happen.

Is there a way to import the function telling Python to ignore the package's __init__.py?

David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • 1
    Why do you want to ignore the `__init__.py` – Jakob Bowyer Dec 07 '12 at 13:25
  • 1
    I'm not entirely sure what you mean by "but it can't happen." But the short answer is no, you can't tell python to ignore the file. There are probably other tricks you could play with `sys.path` to make it work, but they'd be hacks at best. Perhaps you can restructure things so that you `__init__.py` is empty? Or at least doesn't cause any undesired side-effects? – John Szakmeister Dec 07 '12 at 13:27
  • Check this out , http://stackoverflow.com/questions/7533480/why-is-init-py-not-being-called – DoOrDoNot Mar 12 '15 at 20:18

1 Answers1

7

The answer is No, you can't import a python package without the __init__.py being executed. By definition, to make a package, you must put in that directory a __init__.py.

But, you can make an empty __init__.py file.

If you want just to import a function from a module, you can use:

import sys
sys.path.append('path_to_package/')

from module import some_function

Note that this is a dirty solution, and won't always work.

kaspersky
  • 3,959
  • 4
  • 33
  • 50
  • 6
    You say this is a dirty solution but what is the best practice if you want to expose just one specific function from a module whilst there are multiple functions defined in the module? – stedes Jun 04 '20 at 15:32
  • The author was not saying `from ... import ...` is a dirty solution. He was saying the previous `sys.path.append('path_to_package/')` is dirty. – Bruce Aug 26 '23 at 03:55