유지성
유지성

Reputation: 1

How to import through another file in python

I want to cut down on the lines of code that do the import.

In foo.py, there are several imports.

from a import aa
from b import bb
from c import cc

I want to change it like this in foo.py

from bar import wonderful_import  #just one line

and bar.py is probably like this

from a import aa
from b import bb
from c import cc

# or

def wonderful_import():
   from a import aa
   from b import bb
   from c import cc

But this doesn't work as I expected. How can I shorten the import line?

Upvotes: 0

Views: 34

Answers (2)

user15801675
user15801675

Reputation:

Here is some code you can refer to. Also, to import everything from a python file, you can use a *. In your case, it is from bar import *

bbdf.py

print("Hello World 2")

focd.py

print("Hello World")

dc.py

def change():
    import focd
    import bbdf

main.py

import dc
dc.change()

So when I run the file: Output:

Hello World  
Hello World 2

Upvotes: 0

user2599052
user2599052

Reputation: 1136

If you want to import everything from a module called bar, you do this in another module say foo

from bar import *

Upvotes: 2

Related Questions