Reputation: 6968
I have the following structure in my project:
+main_proj
+modules
+user_ops
-add_user.py
-remove_user.py
-__init.py
+common
-user_operations.py
-__init__.py
-main.py
-__init__.py
My problem is that add_user.py
and remove_user.py
both depend on user_operations
and when I try to call them, I get a relative import in non-package
error.
Main.py
from common import user_operations as user_operations #This works ok
if __name__ == '__main__':
command = "remove_user"
#Load usage, functions and paths to modules
__doc__, function_dictionary, modules = utilities.load_modules()
#Get function from dictionary
func = function_dictionary[command]
#Execute function
result = func(api_root, arguments, simulate, headers)
The module that gets called by func(api_root, arguments, simulate, headers)
remove_user_front.py
from ...common import user_operations as user_operations
def remove_user_front(api_root, arguments, simulate, headers):
#Get users in this account
users = user_operations.get_users(api_root, arguments["<source_account>"], headers)
#This is smelly
if arguments["--id"]:
type = "id"
elif arguments["--username"]:
type = "username"
#End smell
result = remove_user(api_root, arguments["<source_account>"], arguments["<user_id>"], type, simulate, headers)
if not result:
return False
else:
return True
function_dictionary = {"remove_user" : remove_user_front}
Error:
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensio
ns\Microsoft\Python Tools for Visual Studio\2.0\visualstudio_py_util.py", line 7
6, in exec_file
exec(code_obj, global_variables)
File "C:\Users\mryan\Documents\Code\cli\cli_front.py", line
70, in <module>
recovery.start_recovery(recovery_file, auto_recovery, headers, modules)
File "C:\Users\mryan\Documents\Code\cli\recovery.py", line 1
01, in start_recovery
imported_module = imp.load_source('recovery',module)
File "C:\Users\mryan\Documents\Code\cli\modules\cam_ops\
remove_user_front.py", line 1, in <module>
from ...common import user_operations as user_operations
ValueError: Attempted relative import in non-package
Does anybody know how I can keep my file structure and enable modules under modules
to use modules under common
?
Upvotes: 3
Views: 9942
Reputation: 197
When your application starts up it get's an os.path attributed.
Each modules that will try to import anything will have that same path. It means that your files in common that will need to import something out of user_ops will need to import it like if it was your main.py which would import them.
try
from modules.user_ops import add_user
in your user_operations
Upvotes: 2