2

I’m unclear on this: __init__.py describes the current folder as a module, no?

So if my top level project folder, my_project, contains file config.py (my_project/config.py), then the file in my_project/drivers/sales/customer.py should be able to import the config.py module simply by:

  • import my_project.config (Errors to: ModuleNotFoundError: No module named 'my_project')
  • Or, from .. import config (Errors to: ValueError: attempted relative import beyond top-level package) - Btw, tried with three dots (...) with same error.
  • Or, simply import config (Errors to: ModuleNotFoundError: No module named 'config')

with the following terminal command:

(env) localhost:/Users/myname/Sites/my_project
$ python drivers/sales/customer.py 

How can I accomplish this import?

Versions:

$ python
Python 3.6.2 (default, Jul 17 2017, 16:44:45) 
user3871
  • 12,432
  • 33
  • 128
  • 268
  • Blowed my head recently too, im think in your case its: from .. import config as your file is 2 level deep, so 2 dots – Kris Nov 15 '17 at 13:52
  • @Kris same error. See above – user3871 Nov 15 '17 at 13:54
  • Ok, last try: did you tried adding a empty __init__.py in the sales folder and then try it with from .. import config? Sorry if this feels like guessing (bc. it is !), but i still cant wrap my head arround python relative imports... – Kris Nov 15 '17 at 14:03
  • All folders in the hierarchy need to have __init__.py file – Abhijeetk431 Nov 15 '17 at 14:04
  • @Kris I was wondering how but ow I know why your init is in bold :) – Abhijeetk431 Nov 15 '17 at 14:05

1 Answers1

0

One way is to expose the path of your project as below:

import sys
sys.path.append('path/to/your/project') # /Users/nabin/Desktop in my case 

#I have "my_project" in Desktop i.e /Users/nabin/Desktop/my_project

Then you can do the following

from my_project import config

So when combined, what you need is following:

import sys
sys.path.append('path/to/your/project')

from my_project import config
Nabin
  • 11,216
  • 8
  • 63
  • 98