MCPcopy
hub / github.com/pallets/werkzeug / import_string

Function import_string

src/werkzeug/utils.py:573–609  ·  view source on GitHub ↗

Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If `sil

(import_name: str, silent: bool = False)

Source from the content-addressed store, hash-verified

571
572
573def import_string(import_name: str, silent: bool = False) -> t.Any:
574 """Imports an object based on a string. This is useful if you want to
575 use import paths as endpoints or something similar. An import path can
576 be specified either in dotted notation (``xml.sax.saxutils.escape``)
577 or with a colon as object delimiter (``xml.sax.saxutils:escape``).
578
579 If `silent` is True the return value will be `None` if the import fails.
580
581 :param import_name: the dotted name for the object to import.
582 :param silent: if set to `True` import errors are ignored and
583 `None` is returned instead.
584 :return: imported object
585 """
586 import_name = import_name.replace(":", ".")
587 try:
588 try:
589 __import__(import_name)
590 except ImportError:
591 if "." not in import_name:
592 raise
593 else:
594 return sys.modules[import_name]
595
596 module_name, obj_name = import_name.rsplit(".", 1)
597 module = __import__(module_name, globals(), locals(), [obj_name])
598 try:
599 return getattr(module, obj_name)
600 except AttributeError as e:
601 raise ImportError(e) from None
602
603 except ImportError as e:
604 if not silent:
605 raise ImportStringError(import_name, e).with_traceback(
606 sys.exc_info()[2]
607 ) from None
608
609 return None
610
611
612def find_modules(

Callers 2

find_modulesFunction · 0.85
__init__Method · 0.85

Calls 1

ImportStringErrorClass · 0.85

Tested by

no test coverage detected