2 ms·
> - performance hit every time the function is called Python modules are always singletons, regardless of where they are imported. "import foo" inside a functi
by formerly_proven 4y ago
> - performance hit every time the function is called
Python modules are always singletons, regardless of where they are imported. "import foo" inside a function will only import the module once (=global effect) but bind the name every time (=local, but cheap, effect).
- Avery3R 4y agoBut you're still getting the perf hit of calling a function and checking if the module is already loaded
- deleted 4y ago[deleted]
- dagmx 4y agoIt’s a fairly simple dict lookup. The same lookup would happen when you use something from that module, so it’s fairly insignificant in the grand scheme. Besides, it’s Python. It’s not going to be super fast anyway. That extra check is never going to show up on a perf trace.
- formerly_proven 4y agoYeah well there's never been a line of Python that's free
- gavinsyancey 4y agoWith one exception -- whatever module is executing is named `__main__`, and if something else imports it by it's usual module name you'll get a duplicate copy.
- jwilk 4y agoExample: $ cat spam.py import sys print(f'__name__ = {__name__!r}') for (name, mod) in sys.modules.items(): try: if 'spam' not in (mod.__file__ or ''): continue except AttributeError: continue print(f'sys.modules[{name!r}] = {mod!r} @ 0x{id(mod):x}') import spam $ python3 -m spam __name__ = '__main__' sys.modules['__main__'] = <module 'spam' from '/home/jwilk/spam.py'> @ 0xf7d86ed8 __name__ = 'spam' sys.modules['__main__'] = <module 'spam' from '/home/jwilk/spam.py'> @ 0xf7d86ed8 sys.modules['spam'] = <module 'spam' from '/home/jwilk/spam.py'> @ 0xf7caef78 More generally, Python is happy to import the same file multiple times as long as the module name is different. For example, if there's eggs/bacon/spam.py and you add both "eggs" and "eggs/bacon" to sys.path, you will have two different modules imported after "import bacon.spam, spam".