2

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
Markku K.
  • 3,840
  • 19
  • 20
summer
  • 213
  • 3
  • 12
  • no. terrible. use functions. – shx2 Nov 15 '13 at 20:25
  • Please clarify what you mean by "add another script inside the first" – Janne Karila Nov 15 '13 at 20:27
  • maybe help: http://stackoverflow.com/questions/5027352/how-to-test-if-one-python-module-has-been-imported – Farhadix Nov 15 '13 at 20:32
  • I don't see any issues with that. Although it is easier to maintain the code when all imports are in one place (typically at the begining of the file). However that's not mandatory. – freakish Nov 15 '13 at 20:36
  • 2
    Doing `if abilitaPippo:` is the same as `if abilitaPippo == True:`. The `== True` does nothing. –  Nov 15 '13 at 20:44
  • @iCodez unless `abilitaPippo` is an instance of a class that overrides `__eq__` to handle checking equality with `True` in some special way. Probably isn't, but just saying, if we want to be pedantic and all. – ely Nov 15 '13 at 20:50

2 Answers2

1

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
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
1

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.

codedstructure
  • 796
  • 7
  • 16