[Python] Python 3 type hinting for dynamic attributes through __getattr__ [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 3, 2025.

  1. Stack

    Stack Membro Participativo

    To wrap all function calls of a module and access it via an wrapper class's __getattr__ method, I tried to use typing library but I could not figure out on how to do this correctly.

    import interface

    """
    >>> print(interface.__all__)
    ['execute_foo_operation', ...]
    """

    class InterfaceWrapper(object):
    def __init__(self, job_queue):
    self.job_queue = job_queue
    self.callbacks = []

    def __getattr__(self, name):
    func = getattr(interface, name)
    return functools.partial(self._wrapper, func)

    def _wrapper(self, func, *args, **kwargs):
    job = func(*args, **kwargs)
    self.job_queue.push(job)
    for callback in self.callbacks:
    callback(job)
    return job

    def register_callback(self, callback):
    self.callbacks.append(callback)


    class Operator(object):
    def __init__(self, job_queue):
    self.interface = InterfaceWrapper(job_queue)

    def after_queuing(self):
    # do something

    def execute_foo_operation(self):
    self.interface.register_callback(self.after_queuing)
    self.interface.execute_foo_operation() # unresolved attribute



    Can anyone guide my code to work correctly?

    Continue reading...

Compartilhe esta Página