开发者

How do I share a python script's imports with another script?

开发者 https://www.devze.com 2023-02-20 10:03 出处:网络
Let\'s say I have a script1.py with 开发者_运维百科imports. How can I share script1.py imports with script2.py? without copy and pasting.Your application should consist of many modules that are logic

Let's say I have a script1.py with 开发者_运维百科imports.

How can I share script1.py imports with script2.py? without copy and pasting.


Your application should consist of many modules that are logically independent. It makes your program easier to read, debug etc. Just like Python's standard library is divided into many modules (as you said - you have to import things from many of them).

The more modules you have, the fewer imports you need to do in each of them. It's because each separate part of your program only imports what it needs. Thanks to this attitude you and other programmers can easily understand the code.

Another way to deal with it (not really recommended):

imports.py: (in this example I assume you put it in the same directory as test.py)

from datetime import date
from re import *

test.py:

from imports import * #you import your imports

today = date.today() #using what you imported in imports.py
print(today)

It might be dangerous due to possibly same names imported. Be careful!


though I agree with the comments... you can have a module that defines the all attribute

from crazyapp import all, my, imports

__all__ =['all', 'my', 'imports']

then just call to import the modules.

from allmyimports import *

But fix things if you have that many.... 200? Think of a module as something that does one thing and does that one thing good. you'll find your imports will drop for the most part.

0

精彩评论

暂无评论...
验证码 换一张
取 消