Return the module an object was defined in, or None if not found.
(object, _filename=None)
| 920 | _filesbymodname = {} |
| 921 | |
| 922 | def getmodule(object, _filename=None): |
| 923 | """Return the module an object was defined in, or None if not found.""" |
| 924 | if ismodule(object): |
| 925 | return object |
| 926 | if hasattr(object, '__module__'): |
| 927 | return sys.modules.get(object.__module__) |
| 928 | |
| 929 | # Try the filename to modulename cache |
| 930 | if _filename is not None and _filename in modulesbyfile: |
| 931 | return sys.modules.get(modulesbyfile[_filename]) |
| 932 | # Try the cache again with the absolute file name |
| 933 | try: |
| 934 | file = getabsfile(object, _filename) |
| 935 | except (TypeError, FileNotFoundError): |
| 936 | return None |
| 937 | if file in modulesbyfile: |
| 938 | return sys.modules.get(modulesbyfile[file]) |
| 939 | # Update the filename to module name cache and check yet again |
| 940 | # Copy sys.modules in order to cope with changes while iterating |
| 941 | for modname, module in sys.modules.copy().items(): |
| 942 | if ismodule(module) and hasattr(module, '__file__'): |
| 943 | f = module.__file__ |
| 944 | if f == _filesbymodname.get(modname, None): |
| 945 | # Have already mapped this module, so skip it |
| 946 | continue |
| 947 | _filesbymodname[modname] = f |
| 948 | f = getabsfile(module) |
| 949 | # Always map to the name the module knows itself by |
| 950 | modulesbyfile[f] = modulesbyfile[ |
| 951 | os.path.realpath(f)] = module.__name__ |
| 952 | if file in modulesbyfile: |
| 953 | return sys.modules.get(modulesbyfile[file]) |
| 954 | # Check the main module |
| 955 | main = sys.modules['__main__'] |
| 956 | if not hasattr(object, '__name__'): |
| 957 | return None |
| 958 | if hasattr(main, object.__name__): |
| 959 | mainobject = getattr(main, object.__name__) |
| 960 | if mainobject is object: |
| 961 | return main |
| 962 | # Check builtins |
| 963 | builtin = sys.modules['builtins'] |
| 964 | if hasattr(builtin, object.__name__): |
| 965 | builtinobject = getattr(builtin, object.__name__) |
| 966 | if builtinobject is object: |
| 967 | return builtin |
| 968 | |
| 969 | |
| 970 | class ClassFoundException(Exception): |