0

I am learning to use python and I need to use three specific modules repeatedly. I don't want to keep importing them over and over again whenever I am working on a new script. So I was wondering how I could point python to always use those modules at startup?

Thanks!

  • 4
    " I don't want to keep importing them over and over again whenever I am working on a new script." Why not? That's normally how it is done. It is good to clearly and explicitly perform your imports. – juanpa.arrivillaga Jun 15 '20 at 20:40
  • From [the zen of python](https://www.python.org/dev/peps/pep-0020/), “Explicit is better than implicit.” – Moon Jun 15 '20 at 20:47
  • You will read your code many more times than you write it, so a little more typing is a small price to pay for greater clarity. – alani Jun 15 '20 at 20:53

1 Answers1

0

I agree with everyone else here re: explicitness, but I'm going to note a corner case you might see in the wild. I would not structure your code this way, but I've seen it.


If you structure your code as:

+ mypackage/
 +  my_math.py
 +  foo.py

my_math.py:

import math

foo.py:

from my_math import *
if math.sin(0) == 0:
    print("foo.py imported math from my_math! It was very effective!")

Then foo will not raise a NameError when run.


The reason I mention this is that you might see the following in some repos:

+ mypackage/
+   __init__.py
+   foo.py

__init__.py:

import math

foo.py:

from mypackage import *
if math.sin(0) == 0:
    print("foo.py import math from mypackage implicitly, via __init__.py")

Then if foo.py is run, it will not error. Again, do follow the majority advice here. Just import in each file. The above is just a sidenote.

Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
tomaszps
  • 66
  • 1
  • 6