1"""
2A simple utility to import something by its string name.
3"""
4
5# Copyright (c) IPython Development Team.
6# Distributed under the terms of the Modified BSD License.
7from __future__ import annotations
8
9from typing import Any
10
11
12def import_item(name: str) -> Any:
13 """Import and return ``bar`` given the string ``foo.bar``.
14
15 Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
16 executing the code ``from foo import bar``.
17
18 Parameters
19 ----------
20 name : string
21 The fully qualified name of the module/package being imported.
22
23 Returns
24 -------
25 mod : object
26 The imported object: for a dotted name ``foo.bar``, the ``bar``
27 attribute of module ``foo`` (which may be any object); for an
28 un-dotted name, the module itself.
29 """
30 if not isinstance(name, str):
31 raise TypeError(f"import_item accepts strings, not '{type(name)}'.")
32 parts = name.rsplit(".", 1)
33 if len(parts) == 2:
34 # called with 'foo.bar....'
35 package, obj = parts
36 module = __import__(package, fromlist=[obj])
37 try:
38 pak = getattr(module, obj)
39 except AttributeError as e:
40 raise ImportError(f"No module named {obj}") from e
41 return pak
42 else:
43 # called with un-dotted string
44 return __import__(parts[0])