1

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.

Alwin
  • 321
  • 2
  • 14

1 Answers1

1

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}"
Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
  • Neat, I hadn't thought of `@classmethod` as I was only using `@staticmethod` to group similar tui menu functions together. Is there a way to avoid having to write `cls.ascii`? – Alwin Nov 13 '21 at 00:41
  • You write `cls.ascii` in every copy of the code you write, so it's still the cut-and-paste into every piece of code you put this. The whole goal is that you need a way to refer to *this specific* method `ascii()`, and certainly not the global function by that name. So, no, I don't think so. – Frank Yellin Nov 13 '21 at 00:52
  • Thanks, I've marked this as an answer since it solves my design pattern problem – Alwin Nov 23 '21 at 02:29