Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use dotty-dict #57

Open
ric-evans opened this issue Jun 22, 2022 · 1 comment
Open

Use dotty-dict #57

ric-evans opened this issue Jun 22, 2022 · 1 comment
Assignees
Labels
enhancement New feature or request

Comments

@ric-evans
Copy link
Member

replace this:

def resolve_attr(
self, var_name: str, typ: Union[None, type, Tuple[type, ...]] = None
) -> Any:
"""Retrieve the instance at `var_name` from signature-parameter args.
Optionally, check if the value is of type(s), `type`.
Searches:
- non-callable objects
- supports nested/chained attributes (including `self.*` attributes)
- supports literal dict-member access in dot syntax,
+ ex: for bam['boom'] use bam.boom
Examples:
signature -> (self, foo)
variable names -> self.green, foo, foo.bar.baz, foo.bam.boom
Raises:
AttributeError -- if var_name is not found
TypeError -- if the instance is found, but isn't of the type(s) indicated
"""
LOGGER.debug(f"rget({var_name}, {typ})")
def dot_left(string: str) -> str:
return string.split(".", maxsplit=1)[0]
def dot_right(string: str) -> str:
try:
return string.split(".", maxsplit=1)[1]
except IndexError:
return ""
def _get_attr_or_value(obj: Any, attr: str) -> Any:
if isinstance(obj, dict):
return obj.get(attr, None)
else:
return getattr(obj, attr)
def _rget(obj: Any, attr: str) -> Any:
if not attr:
return obj
elif "." in attr:
left_attr = _get_attr_or_value(obj, dot_left(attr))
return _rget(left_attr, dot_right(attr))
else:
return _get_attr_or_value(obj, attr)
try:
obj = _rget(self.param_args[dot_left(var_name)], dot_right(var_name))
except AttributeError as e:
raise AttributeError( # pylint: disable=W0707
f"'{var_name}': {e} "
f"(present parameter arguments: {', '.join(self.param_args.keys())})"
)
except KeyError:
raise AttributeError( # pylint: disable=W0707
f"'{var_name}': function parameters have no argument '{dot_left(var_name)}' "
f"(present parameter arguments: {', '.join(self.param_args.keys())})"
)
if typ and not isinstance(obj, typ):
raise TypeError(f"Instance '{var_name}' is not {typ}")
return obj

with this: pypi.org/project/dotty-dict

@ric-evans ric-evans added the enhancement New feature or request label Jun 22, 2022
@ric-evans ric-evans self-assigned this Jun 22, 2022
@ric-evans
Copy link
Member Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant