Skip to content Skip to sidebar Skip to footer

Optionally Use Decorators On Class Methods

Im new to Python, and im building a wrapper for an api. I would want to let the user decide if he/she wants to use a decorator on methods I expose from my module. For example: # cr

Solution 1:

Your options are to add more methods to your API or to provide the user with utility functions instead:

from yourmodule import MyAPI

api = MyAPI

filtered_timetable = api.filter_on(something)

or

from yourmodule import MyAPI, filter_timetable

api = MyAPI

filtered_timetable = filter_timetable(api.time_table, something)

Remember that decorators are just callables; the syntax:

@foo
def bar():
    pass

is just syntactic sugar for:

def bar():
    pass
bar = foo(bar)

foo() is called, and the return value replaces the decorated object. Usually you use functions for decorators, but nothing says you have to use those functions only as decorators.

filter_timetable could be such a decorator; if you have a usecase for using it as both.


Post a Comment for "Optionally Use Decorators On Class Methods"