-1

I have defined a method foo and a class bar that has a method foo_bar in __init__.py file

dir/
   __init__.py
   runme.py

Now I want to import __init__.py from runme.py

I have tried

# in runme.py

from . import foo

foo()

and

import foo

foo()

But neither works. I'm using Python 3.7 and Windows 10 Home

I have read How to import classes defined in __init__.py and done some research.

Python's exception is:

ImportError: attempted relative import with no known parent package
# __ init __.py 

def foo():
   print("Im Foo") 
class bar:
    def __init__():
        pass
    def foo_bar(self):
        print("Im Foo_Bar in class bar")
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Zer0
  • 9
  • 1
  • 8

1 Answers1

1

If pkg is your main packages, you can import it (aka the pkg/__init__.py file) doing:

import pkg

If you want the foo_bar function in this package, you can write:

from pkg import foo_bar

So, in runme.py module, you can do:

from pkg import foo_bar

foo_bar(...)

Of course, you need to call your runme.py module from the root directory (the parent of pkg directory):

python pkg/runme.py
# or
python -m pkg.runme

Please, consider reading Executing modules as scripts

EDIT 1

You can add your project root directory to sys.path:

# in `runme.py`:
def _fix_sys_path():
    import os
    import sys

    HERE = os.path.abspath(os.path.dirname(__file__))  # /path/to/project_dir/pkg
    PROJECT_DIR = os.path.dirname(HERE)  # /path/to/project_dir
    sys.path.insert(0, PROJECT_DIR)


_fix_sys_path()
from pkg import foo_bar

foo_bar(...)
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103