Skip to content

Decrator utils #95

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Conversation

dev0Guy
Copy link
Contributor

@dev0Guy dev0Guy commented Dec 29, 2024

User description

rewrite some of the decrator utils.
By converting for loops into list, dict comprehension , I've a lot of wrapped try, exception section inside the loop with re-raise, I've removed them (there is no unique logic inside the exception block).

Original

def get_non_dependencies_params(cls):
    source = inspect.getsource(cls.__init__).strip()
    tree = ast.parse(source)
    non_dependencies = {}
    for node in ast.walk(tree):
        if isinstance(node, ast.Attribute):
            non_dependencies[node.attr] = node.value.id
    return non_dependencies

Changed

def get_non_dependencies_params(cls: Type):
    source = inspect.getsource(cls.__init__).strip()
    tree = ast.parse(source)
    return {
        node.attr: node.value.id
        for node in ast.walk(tree)
        if isinstance(node, ast.Attribute)
    }

Forthermore, I've seen duplicate code inside get_instance_variables where the dependencies is already written inside parse_dependencies.

dependencies = set(
    param.name
    for param in inspect.signature(cls.__init__).parameters.values()
    if param.annotation != param.empty
    and getattr(param.annotation, "__injectable__", False)
)
def parse_dependencies(cls):
    signature = inspect.signature(cls.__init__)
    dependecies = {}
    for param in signature.parameters.values():
        try:
            if (
                param.annotation != param.empty
                and hasattr(param.annotation, "__dict__")
                and INJECTABLE_TOKEN in param.annotation.__dict__
            ):
                dependecies[param.name] = param.annotation
        except Exception as e:
            raise e
    return dependecies

I didn't understand why the need to check only object ( not including inherited attributes) however I assume a usage and created another argument for parse_dependencies to decide which check to activate.
and got:

def parse_dependencies(cls: Type, check_inherited: bool = False) -> Dict[str, Type]:
    """
    Returns:
        mapping of injectable parameters name to there annotation
    """
    signature = inspect.signature(cls.__init__)
    filter_by = (
        _check_injectable_inherited
        if check_inherited
        else _check_injectable_not_inherited
    )
    params: Iterable[inspect.Parameter] = filter(filter_by, signature.parameters.values())
    return {param.name: param.annotation for param in params}

Generated description

Below is a concise technical summary of the changes proposed in this PR:

Refactors and optimizes utility functions in the nest/core/decorators/utils.py file. Converts for loops into list and dictionary comprehensions, removes unnecessary try-except blocks, and introduces type hints. Adds new helper functions to improve code readability and maintainability. Modifies the parse_dependencies function to handle both inherited and non-inherited injectable attributes.

TopicDetails
Code Optimization Refactors utility functions to improve performance and readability
Modified files (1)
  • nest/core/decorators/utils.py
Latest Contributors(2)
UserCommitDate
itay.dar@lemonade.comfeat-build-cli-apps-wi...August 06, 2024
amirm.lavasani@gmail.comAdd-HTTP-Status-Code-F...June 24, 2024
Dependency Handling Enhances dependency parsing with options for inherited and non-inherited attributes
Modified files (1)
  • nest/core/decorators/utils.py
Latest Contributors(2)
UserCommitDate
itay.dar@lemonade.comfeat-build-cli-apps-wi...August 06, 2024
amirm.lavasani@gmail.comAdd-HTTP-Status-Code-F...June 24, 2024
This pull request is reviewed by Baz. Join @dev0Guy and the rest of your team on (Baz).

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

Successfully merging this pull request may close these issues.

1 participant