dinkelk
dinkelk

Reputation: 2786

Importing package only when main is run in python package

I like to test my packages in python using the following code at the bottom of my package:

if __name__ == "__main__":
    sys.exit(main())

where main() is a function I define above. Now my question is this:

I need to import extra packages in my main for testing my module that are NOT necessary to import if a user is just importing my module (ie. from another script). Is there a way to only import these extra packages if my main is explicitly run? And when my package is just imported (ie. from another script), these extra packages are NOT imported.

Upvotes: 2

Views: 2121

Answers (2)

Ngure Nyaga
Ngure Nyaga

Reputation: 3027

In Python, you can place imports at any point in the code.

So you could have:

if __name__ == "__main__":
    import <package> # place your imports here
    sys.exit(main())

"Lazy imports" are discussed in detail in in this question

Upvotes: 3

inspectorG4dget
inspectorG4dget

Reputation: 113975

Why not put your import statements directly in the body of your main()? That should do it.

def main():
   import my_module # import ONLY if main is called
   # code

Upvotes: 4

Related Questions