PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 24, 2022

[FIXED] How to import a module into another module

 August 24, 2022     module, python, python-3.x, python-import     No comments   

Issue

This is the structure of my project:

project (folder)
   main.py
   assets (folder)
      a.py
      b.py

When I import module a into module b and run main.py, I get No module named 'a'.

Yet if I run b.py directly, it imports a.py just fine.

a and b are in the same directory, so what am I missing? FWIW, I am using Python 3.10.

main.py:

import assets.b as bb

a.py:

def func(x):
    print(x)

b.py:

import a
a.func('hello')

Solution

Update your b.py as follows

from . import a 
a.func('hello')

or

from assets import a
a.func('hello')

In first case, we are telling interpreter to check in the same location as file. In second case, we are just using a fullpath. Tested with python 3.10.1 and 3.6

If you are using a folder structure, it is always best to fix you execution path and relative path according to your main.py. Implies running python3.10 b.py from assets is not acceptable.


In case, you want the functionality to do python3.10 b.py from assets folder and also python3.10 main.py then update the code as follows.

try:
  from . import a
except:
  import a

a.func('hello')

If you are sticking to a IDE like PyCharm then such errors are easy to spot and fix.



Answered By - sam
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing