Search code examples
pythonpython-3.xfunctionintrospection

Determine static method qualified name from within itself in python


I'm refactoring some code I wrote to work with an interactive TUI and I wish to use my class structure to create commands rather than explicitly typing out strings. Using __qualname__ would be very handy, but I can't find the equivalent way to call it from within the function?

# Example:
class file:
    class export:
        @staticmethod
        def ascii(output_path):
            return f"/file/export/ascii/ {output_path}"

# Desired
import inspect
class file:
    class export:
        @staticmethod
        def ascii(output_path):
            qualname= inspect.currentframe().f_code.co_qualname  # <-- co_qualname is not implemented
            return f"/{qualname.replace(".", "/")}/ {output_path}"

I understand from https://stackoverflow.com/a/13514318 that inspect.currentframe().f_code.co_name will only return 'ascii' and co_qual_name has not been implemented yet per https://stackoverflow.com/a/12213690 and https://bugs.python.org/issue13672?

Is there a way I can get file.export.ascii from within the ascii() static method itself? Decorators or other design patterns are also an option, but I sadly have hundreds of these static methods.


Solution

  • You can get what you want by making ascii be a class method rather than a static method. You still call it the same way, but you have a way of accessing the method itself from within the method.

    class file:
        class export:
            @classmethod
            def ascii(cls, output_path):
                return f"{cls.ascii.__qualname__}/{output_path}"