in chz/factories.py [0:0]
def from_string(self, factory: str) -> Callable[..., Any]:
if ":" in factory:
module_name, var = factory.split(":", 1)
# fun lambda case
# TODO: add docs for fun lambda case
if module_name == "lambda" or module_name.startswith("lambda "):
default_module = self.default_module
if isinstance(default_module, _MISSING_TYPE) or default_module is None:
eval_ctx = None
else:
eval_ctx = default_module
try:
if isinstance(ast.parse(factory).body[0].value, ast.Lambda): # type: ignore[attr-defined]
return eval_in_context(factory, eval_ctx)
except Exception as e:
raise MetaFromString(
f"Could not interpret {factory!r} as a function: {e}"
) from None
raise AssertionError
# we've just got something explicitly specified
module = _module_from_name(module_name)
match = re.fullmatch(r"(?P<base>[^\s\[\]]+)(\[(?P<generic>.+)\])?", var)
if match is None:
raise MetaFromString(f"Failed to parse {factory!r} as a class name")
base = match.group("base")
generic = match.group("generic")
# TODO: think about this type ignore
typ = _maybe_generic(_module_getattr(module, base), generic, template=self.annotation) # type: ignore[arg-type]
return _return_prospective(typ, self.annotation, factory=factory)
try:
if self.annotation in {object, typing.Any, typing_extensions.Any}:
return _find_subclass(factory, self.annotation)
if typing.get_origin(self.annotation) is type:
base_type = typing.get_args(self.annotation)[0]
assert isinstance(base_type, type)
typ = _find_subclass(factory, base_type)
return lambda: typ
if is_union_type(self.annotation):
if self.original_unspecified is not None:
try:
if is_instantiable_type(self.original_unspecified):
return _find_subclass(factory, self.original_unspecified)
except MetaFromString:
pass
for t in typing.get_args(self.annotation):
try:
if is_instantiable_type(t):
return _find_subclass(factory, t)
except MetaFromString:
pass
if type(None) in typing.get_args(self.annotation) and factory == "None":
return lambda: None
raise MetaFromString(f"Could not produce a union instance from {factory!r}")
if is_instantiable_type(self.annotation):
return _find_subclass(factory, self.annotation)
if self.annotation is None and factory == "None":
return lambda: None
except MetaFromString as e:
try:
default_module = self.default_module
if isinstance(default_module, str):
default_module = _module_from_name(default_module)
if default_module is not None:
obj = _module_getattr(default_module, factory)
return _return_prospective(obj, self.annotation, factory=factory)
except MetaFromString:
pass
raise e
# Probably a special form
raise MetaFromString(
f"Could not produce a {type_repr(self.annotation)} instance from {factory!r}"
)