Making Python scripts work both as imports and executables - is there a clean solution?

Pretty sure if you run it with the -m option, it should work, i.e. python -m mesa.examples.basic.boid_flockers.app.

Otherwise you can also provide a thin __main__.py file so that python -m mesa boid_flockers works by dynamically importing and executing the cirrect example.

Note that e.g. the first solution you listed doesn’t quite work if the file being executed also gets imported by others: if that happens, there are now two versions of that module in memory with duplicate, non-related classes.

In general you should avoid executing python code in such a way that there is an entry in sys.path (e.g. the current directory) that points within a package. That will almost always cause issues at some point.

1 Like