3 ms·
Maybe nothing would break ? edit: ok well "xxx in sys.modules" would indeed be a problem
by simlevesque 1y ago
Maybe nothing would break ?
edit: ok well "xxx in sys.modules" would indeed be a problem
- IshKebab 1y agoYeah unfortunately in real world Python code people put side effects in their modules all the time.
- kstrauser 1y agoIn Python? I almost never see that. And I’ve certainly never signed off on a PR that did that.
- oofbey 1y agoMaybe your code is awesome, but you're almost certainly using a library which does it.
- lyu07282 1y agoThis. The most egregious example I've ever seen is the inflect library, takes almost 2 seconds(!) to import: https://github.com/jaraco/inflect/issues/212 https://github.com/jaraco/inflect/issues/212
- zahlman 1y agoRecursively importing other modules is itself a side effect. In fact, all the code you see in the module is "side effects", in a sense. A `class` body, for example, has to actually run at import time, creating the class object and attaching it as an attribute of the module object. Similarly for functions. Even a simple assignment of a constant actually has to run at module import. And all of these things add up. Further, if there isn't already cached bytecode available for the module, by default it will be written to disk as part of the import process. That's inarguably a side effect.
- flykespice 1y agoSide-effect means you're changing state outside the scope the code is running. Sure thing you can declare globals variable and run anything on a module file global scope (outside funcs and class body), but even that 'global' scope is just an illusion, and everything declared there, as yourself said, is scoped to the module's namespace (and you can't leak the 'globals' when importing the module unless you explicity do so 'from foo import *'. Think of python's import as eval but safer because it doesn't leaks the results from the module execution) So for a module to have side-effect (for me) it would either: - Change/Create attributes from other modules - Call some other function that does side-effect (reflection builtins? IO stuff)
- IshKebab 1y agoOften it's things like registering functions in a global registry, or patching things about how Python works (e.g. adding stuff to the module path).
- kstrauser 1y agoYou’re right. “Side effect” here means that your program’s behavior changes simply by importing something, eg by monkey patching something else. If’s not: * Importing other modules. * Taking a long time to import. * Writing .pyc files. If any program can “import foo” and still execute exactly the same bytecode afterward as before, you can say that foo doesn’t have side effects.