1"""
2A simple utility to import something by its string name.
3
4Vendored form ipython_genutils
5"""
6
7# Copyright (c) IPython Development Team.
8# Distributed under the terms of the Modified BSD License.
9from __future__ import annotations
10
11
12def import_item(name):
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 : module object
26 The module that was imported.
27 """
28
29 parts = name.rsplit(".", 1)
30 if len(parts) == 2:
31 # called with 'foo.bar....'
32 package, obj = parts
33 module = __import__(package, fromlist=[obj])
34 try:
35 pak = getattr(module, obj)
36 except AttributeError:
37 raise ImportError("No module named %s" % obj) from None
38 return pak
39 # called with un-dotted string
40 return __import__(parts[0])