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.