Reputation: 1965
I would like to create a file that import other imports, e.g.
startup.py:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('qt5agg')
...
the just write
import startup
and have all of them.
is it possible?
Upvotes: 0
Views: 92
Reputation: 6590
I suggest you explicitly specify module that you wanted to be imported at the time of star import :)
Try the following example:
#example.py
import time
import random
import collections
__all__ = ['time', 'random']
$ python
>>> from example import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'random', 'time']
See how it didn't import collections
module, because i didn't ask it to :)
Upvotes: 2
Reputation: 828
You can try following:
Let file1 is abc.py
import pandas as pd
import numpy as np
Let file2 is main.py:
import abc
# Use pandas import as temp.pd
df = temp.pd.DataFrame({'A': [1,2,3], 'B': [2,3,4]})
print(df)
Output:
A B
0 1 2
1 2 3
2 3 4
Upvotes: 1
Reputation: 868
Check out this older StackOverflow post which details many different ways to achieve what you want, and especially the excellent comment by 'Eric Leschinski'.
The simplest solution I'd check out first is to make a new directory and declare it as a package by creating an __init__.py
file in there, which would contain the imports.
This dummy "package" of yours will be the input handler, and then from your main script you would from root.parent.folder.file import class/variable/whatever
. The main drawback is that this disallows non-relative paths, but it's okay if all the project is self-contained.
Upvotes: 2
Reputation: 191
You could do something like this
startup.py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
np = np
plt = plt
matplotlib = matplotlib
main.py
from startup import *
plt.show()
It's kinda ugly in my opinion, but works.
Upvotes: 1
Reputation: 36033
It's not recommended for readability, but you could write:
from startup import *
in the file where you want to use np
etc.
Upvotes: 5