summer
summer

Reputation: 213

Python best practices import modules

Got one looping script that run by itself, now I want to add another script inside the first, I've inserted a var at the start of first file, if it's true then load the second module. It work,but I'm wondering if his is a good practice?

if abilitaPippo == True:
    try:
        import Pippo
        Pippoabilitato = True
    except ImportError:
        Pippoabilitato = False
else:
    Pippoabilitato = False

Upvotes: 2

Views: 688

Answers (2)

codedstructure
codedstructure

Reputation: 806

Python modules which 'do things' at global scope become fragile because they work differently when run directly to when they are imported. Also within a Python process a module will only be 'executed' once - on the first import. After that, import detects it's already been loaded and doesn't need to do anything.

Have a look at this: http://plope.com/Members/chrism/import_time_side_effects

This avoidance of side-effects is also the reason for the typical Python idiom

if __name__ == '__main__':
    main()

which you will often in see in scripts run from the command line. When run from the command line, the __name__ global variable is the string 'main', but when a module is imported, __name__ is the name of the module, so nothing is run directly.

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122326

Python is not C with #ifdef and so on and, as such, you should avoid conditional inclusion of code. Or to put it differently: you can do this but it's not recommended practise in Python.

Instead you should figure out what the code should do and then write it based on that. For example, you can pass command-line flags to your script and let the runtime behaviour vary depending on which command-line flags were passed.

That having been said in Python is common to have the following for modules that may or may not be installed:

try:
    import mymodule
except ImportError:
    pass

Upvotes: 1

Related Questions