Return the module an object was defined in, or None if not found.
(object, _filename=None)
| 967 | _filesbymodname = {} |
| 968 | |
| 969 | def getmodule(object, _filename=None): |
| 970 | """Return the module an object was defined in, or None if not found.""" |
| 971 | if ismodule(object): |
| 972 | return object |
| 973 | if hasattr(object, '__module__'): |
| 974 | return sys.modules.get(object.__module__) |
| 975 | # Try the filename to modulename cache |
| 976 | if _filename is not None and _filename in modulesbyfile: |
| 977 | return sys.modules.get(modulesbyfile[_filename]) |
| 978 | # Try the cache again with the absolute file name |
| 979 | try: |
| 980 | file = getabsfile(object, _filename) |
| 981 | except (TypeError, FileNotFoundError): |
| 982 | return None |
| 983 | if file in modulesbyfile: |
| 984 | return sys.modules.get(modulesbyfile[file]) |
| 985 | # Update the filename to module name cache and check yet again |
| 986 | # Copy sys.modules in order to cope with changes while iterating |
| 987 | for modname, module in sys.modules.copy().items(): |
| 988 | if ismodule(module) and hasattr(module, '__file__'): |
| 989 | f = module.__file__ |
| 990 | if f == _filesbymodname.get(modname, None): |
| 991 | # Have already mapped this module, so skip it |
| 992 | continue |
| 993 | _filesbymodname[modname] = f |
| 994 | f = getabsfile(module) |
| 995 | # Always map to the name the module knows itself by |
| 996 | modulesbyfile[f] = modulesbyfile[ |
| 997 | os.path.realpath(f)] = module.__name__ |
| 998 | if file in modulesbyfile: |
| 999 | return sys.modules.get(modulesbyfile[file]) |
| 1000 | # Check the main module |
| 1001 | main = sys.modules['__main__'] |
| 1002 | if not hasattr(object, '__name__'): |
| 1003 | return None |
| 1004 | if hasattr(main, object.__name__): |
| 1005 | mainobject = getattr(main, object.__name__) |
| 1006 | if mainobject is object: |
| 1007 | return main |
| 1008 | # Check builtins |
| 1009 | builtin = sys.modules['builtins'] |
| 1010 | if hasattr(builtin, object.__name__): |
| 1011 | builtinobject = getattr(builtin, object.__name__) |
| 1012 | if builtinobject is object: |
| 1013 | return builtin |
| 1014 | |
| 1015 | |
| 1016 | class ClassFoundException(Exception): |