Jaymon / endpoints

Lightweight REST api backend framework that automatically maps urls to python modules and classes
MIT License
29 stars 10 forks source link

route and version decorators with the same name #101

Closed Jaymon closed 7 months ago

Jaymon commented 4 years ago

I could try to see if I could make this work:

callframe = sys._getframe(1)
namespace = callframe.f_locals

via: In Python, decorate two methods with the same name to distinguish them

Basically, if the method names are the same then I would get the frame and get the locals and save the method under a different name in the class.

search:

Jaymon commented 7 months ago

This actually worked, below is my test code:

def dec(func):
    callframe = sys._getframe(1)
    pout.v(callframe)

    namespace = callframe.f_locals
    pout.v(namespace)
    name = func.__name__
    func_name = b"{}_{}".format(name, random.randint(1, 50000))
    func.__name__ = func_name
    pout.v(name, func_name)
    namespace[func_name] = func
    return func

class Foo(object):
    @dec
    def bar(self, *args, **kwargs):
        pout.v("bar 1: {}".format(args))

    @dec
    def bar(self, *args, **kwargs):
        pout.v("bar 2: {}".format(args))

f = Foo()
#f.bar(1, 2)
pout.i(f)

# tabs I had open:
# https://docs.python.org/2/library/inspect.html#the-interpreter-stack
# https://stackoverflow.com/questions/9026236/how-do-i-get-access-to-all-current-stack-frames-f-globals-attribute
# https://github.com/agronholm/typeguard/pull/63
# https://docs.python.org/3/library/sys.html#sys._getframe
# https://stackoverflow.com/questions/13094242/in-python-decorate-two-methods-with-the-same-name-to-distinguish-them
#
#

# search:
# sys._getframe python support

I've changed how I think about routing and versioning though, so this is no longer needed, because routing between multiple methods is now accomplished via first successful one wins, so it doesn't need to have route or version decorator, those are just another way to narrow the criteria on what it takes to have that method execute successfully.