3 ms·
Don't run any functions at the root level of your module. Instead, if you really need long-lasting objects which get initiated once, then use an object, and pu
by deckiedan 13y ago
Don't run any functions at the root level of your module.
Instead, if you really need long-lasting objects which get initiated once, then use an object, and put any initialisation stuff in it's `__init__` method. Then the module can be imported whenever, but your initialisation stuff is only called when the user of your library creates a new instance of that class.
For bonus points, make your classes able to be used with the `with ...` syntax, so then lifetime is kept to a minimum, and errors/whatever are dealt with by default.
If you really really need to monkey around and take control of the whole python interpreter (gevent, twisted, and possibly some GUI frameworks come to mind...) then don't do that at import time, do it with a `run_forever()` or `take_control` type function.
But yes, a virtualenv for every project does help a lot with not accumulation cruft.
- zipfle 13y agoI sometimes make calls to collections.namedtuple and other class building functions at the same time as the rest of my definitions.
- rcfox 13y agoIf you pass verbose=True to namedtuple(), you can see that it's essentially just defining a new class. This is something that people already do at the top level of a module.