Is it possible to get a properties fully qualified when only property is passed into function?

68 Views Asked by At

I am trying to get fully qualified name from a property.

Example class

class Foo:
    def __init__(self, val: int):
       self._val = val

    @property
    def myval(self) -> int:
        return self._val

I am attempting to get full qualified name of different objects. I am aiming to get a result like ooolib.foo.Foo.myval (module, class, attribute).

The idea is that I want to create a script that can do someting like the following.

>>> from ooolib.helper import hlp
>>> from ooolib.foo import Foo
>>>
>>> hlp(Foo.myval)
Launching help for "ooolib.foo.Foo.myval" at "https://ooolib.help.example.com/src/ooolib/foo/Foo#myval"

I have a backend that contains all the fully qualified names and their respective help page links. I want to make it simple for user to look up help in a python interactive console.

My goal it to have users be able to get help for any part of the Library by typing the actual objects. In the interactive console tab complete is enabled so it makes sense to me to do it this way.

>>> hlp(ooolib.bar.Bar.mymethod)
>>> hlp(ooolib.bar.Bar.some_property)
>>> hlp(ooolib.bar.Bar.some_attr)
>>> hlp(ooolib.foo.Foo.__init__)
>>> hlp(ooolib.foo)

Is this possible of just a lofty goal on my part?

1

There are 1 best solutions below

0
blhsing On

You can subclass property and override the __set_name__ hook to store the property's fully qualified name in an additional attribute such as __qualname__ :

class Property(property):
    def __set_name__(self, owner, name):
        super().__set_name__(owner, name)
        self.__qualname__ = f'{owner.__module__}.{owner.__qualname__}.{name}'

so that:

class Foo:
    def __init__(self, val: int):
       self._val = val

    @Property
    def myval(self) -> int:
        return self._val

print(Foo.myval.__qualname__)

outputs:

__main__.Foo.myval

Demo here

Note that the __qualname__ of a class does not include the module name, unlike what you wish to include for a fully qualified name of a property, so to be consistent you may want to consider not to include the module name when setting __qualname__ for a property either.