MCPcopy Index your code
hub / github.com/ipython/ipython / get_parent

Function get_parent

IPython/lib/deepreload.py:49–120  ·  view source on GitHub ↗

parent, name = get_parent(globals, level) Return the package that an import is being performed in. If globals comes from the module foo.bar.bat (not itself a package), this returns the sys.modules entry for foo.bar. If globals is from a package's __init__.py, the package's en

(globals, level)

Source from the content-addressed store, hash-verified

47 builtin_mod.__import__ = saved_import
48
49def get_parent(globals, level):
50 """
51 parent, name = get_parent(globals, level)
52
53 Return the package that an import is being performed in. If globals comes
54 from the module foo.bar.bat (not itself a package), this returns the
55 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
56 the package's entry in sys.modules is returned.
57
58 If globals doesn't come from a package or a module in a package, or a
59 corresponding entry is not found in sys.modules, None is returned.
60 """
61 orig_level = level
62
63 if not level or not isinstance(globals, dict):
64 return None, ''
65
66 pkgname = globals.get('__package__', None)
67
68 if pkgname is not None:
69 # __package__ is set, so use it
70 if not hasattr(pkgname, 'rindex'):
71 raise ValueError('__package__ set to non-string')
72 if len(pkgname) == 0:
73 if level > 0:
74 raise ValueError('Attempted relative import in non-package')
75 return None, ''
76 name = pkgname
77 else:
78 # __package__ not set, so figure it out and set it
79 if '__name__' not in globals:
80 return None, ''
81 modname = globals['__name__']
82
83 if '__path__' in globals:
84 # __path__ is set, so modname is already the package name
85 globals['__package__'] = name = modname
86 else:
87 # Normal module, so work out the package name if any
88 lastdot = modname.rfind('.')
89 if lastdot < 0 < level:
90 raise ValueError("Attempted relative import in non-package")
91 if lastdot < 0:
92 globals['__package__'] = None
93 return None, ''
94 globals['__package__'] = name = modname[:lastdot]
95
96 dot = len(name)
97 for x in range(level, 1, -1):
98 try:
99 dot = name.rindex('.', 0, dot)
100 except ValueError as e:
101 raise ValueError("attempted relative import beyond top-level "
102 "package") from e
103 name = name[:dot]
104
105 try:
106 parent = sys.modules[name]

Callers 1

deep_import_hookFunction · 0.85

Calls 1

getMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…