1

I have implemented the following decorators:

class alias(object):

    """
    A decorator for implementing method aliases.
    """

    def __init__(self, *aliases):

        self.aliases = set(aliases)

    def __call__(self, obj):

        if type(obj) == property:
            obj.fget._aliases = self.aliases
        else:
            obj._aliases = self.aliases

        return obj

def aliased(aliased_class):

    """
    A decorator for enabling method aliases.
    """

    aliased_class_dict = aliased_class.__dict__.copy()
    aliased_class_set = set(aliased_class_dict)

    for name, method in aliased_class_dict.items():

        aliases = None

        if (type(method) == property) and hasattr(method.fget, '_aliases'):
            aliases = method.fget._aliases
        elif hasattr(method, '_aliases'):
            aliases = method._aliases

        if aliases:

            for a in aliases - aliased_class_set:
                setattr(aliased_class, a, method)

    return aliased_class

Below, an example of how I'm using them in order to create callable aliases of properties and methods:

@aliased
class MyClass(object):

    @alias('a')
    @property
    def alpha(self) -> float:

        """
        Returns the value of alpha.
        """

        return 2.5

    @alias('agt')
    def alpha_greater_than(value) -> bool:

        """
        Checks whether alpha is greater than the given value.
        """

        return self.alpha > value

mc = MyClass()
result = mc.agt(3.0)
# ...

Now I'm packaging out my project and building the documentation. At present, aliased methods and properties "inherit" the same docstring of the original entity. I would like to know if it's possible to manipulate the docstrings of aliased entities, at decorator level, so that they look like:

This method/property is an alias of X.

1 Answer 1

2

You do can directly manipulate X.__doc__ such as:

if aliases:

    for a in aliases - aliased_class_set:
        method.__doc__ = "This function is an alias of %s." % a
        setattr(aliased_class, a, method)

But the problem is that the original reference X will also be influenced. So you should better use a wrapper:

def aliased(aliased_class):

    """
    A decorator for enabling method aliases.
    """
    def wrapper(func):
        @functools.wraps(func)
        def inner(*args, **kwargs):
            return func(*args, **kwargs)
        return inner

    aliased_class_dict = aliased_class.__dict__.copy()
    aliased_class_set = set(aliased_class_dict)

    for name, method in aliased_class_dict.items():

        aliases = None

        if (type(method) == property) and hasattr(method.fget, '_aliases'):
            aliases = method.fget._aliases
        elif hasattr(method, '_aliases'):
            aliases = method._aliases

        if aliases:

            for a in aliases - aliased_class_set:
                wrapped_method = wrapper(method)
                wrapped_method.__doc__ = "This function is an alias of %s." % a
                setattr(aliased_class, a, wrapped_method)

    return aliased_class

And test:

print(mc.alpha_greater_than.__doc__)
print(mc.agt.__doc__)

Output:

        Checks whether alpha is greater than the given value.

This function is an alias of agt.
3
  • This works like a charm except for the fact that aliased entities lose their signature ant type hints in the Sphinx documentation. "agt(value) -> bool", for example, becomes "agt(**kwargs)". Is there any way to preserve it? Jan 11, 2019 at 21:59
  • Well, I didn't test it but I believe there is. I will modify my answer to use functools.wraps
    – Sraw
    Jan 11, 2019 at 22:01
  • 1
    @TommasoBelluzzo I've checked that functools.wraps works perfectly :) See my update.
    – Sraw
    Jan 11, 2019 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.