1

I am aware there've been discussions on this topic. My case might be kind of 'special'. My code bar.py needs to use a module, let's say, foo. The general usage of bar.py is something like this:

python bar.py --threads 3 --dir jjj

The issue is that loading foo takes a long time(~40s), so I want to check the correctness of the arguments before loading it. Does it make sense to put import foo later in the code instead of at the top?

2 Answers2

6

You can technically import a module wherever you like, but note that it will become a local name; if imported in the middle of a class or function then it will be in only that scope, not in global (module) scope.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4

Yes, in Python you are allowed to import modules anywhere you like in a Python file. However, the scope matters. For example, if you import foo globally the module is available globally, like so:

import foo

# you can use `foo` here

def main():
    # you can use `foo` here too

# ...

However, if you import inside of a class or function, that module is only available within that scope. For example:

def main():
    import foo

    # `foo` is available here (scope of `foo`)

    def validate_something():
        # `foo` is available here because `validate_something` has a child scope of the `main` function's scope

def parse_args():
    # `foo` is not available here (scope of `parse_args`)

# `foo` is also not available here (the global scope)

Now, in your "special" case, yes it would be ideal to delay the import until the arguments are parsed and validated. The only downside to imports in the middle of a file are organization, but this is a necessary trade-off in scenarios that make sense.

Zach King
  • 798
  • 1
  • 8
  • 21