Decorator for Unimplemented (Python) Functions

61 views
Skip to first unread message

tbp1...@gmail.com

unread,
Mar 11, 2021, 3:15:03 PM3/11/21
to leo-editor
Here is a little trick to catch functions or methods that you haven't implemented yet.  It's useful when you sketch out the structure of a program but the functions/methods don't do anything yet.  Typically you write the signature of the function but the only line of code is pass.

The last line of the function must be pass for this to work. 
import inspect
import sys
def notImplemented(f):
    """Decorator to announce when the decorated function has
    not been implemented.  The last line of the function
    must be "pass" for this to work.
    """
    _name = f.__name__
    def new_f(*args):
        _lines = inspect.getsourcelines(f)[0]
        if _lines[-1].strip() == 'pass' :
            print(f'{_name} not implemented')
            sys.exit(2)
        else:
            return f(*args)
    return new_f


Typical usage:

@notImpemented
def func1(arg1, arg2):
    """A function in the middle of being developed."""
    for s in arg1:
        words = s.split()
        # we're still working on it, more to come tomorrow

    pass # Comment out this line when you work on the code

Now when you try to run your program, the output will politely tell you which function you called but you forgot that it isn't finished yet.

Edward K. Ream

unread,
Mar 11, 2021, 3:26:43 PM3/11/21
to leo-editor
On Thu, Mar 11, 2021 at 2:15 PM tbp1...@gmail.com <tbp1...@gmail.com> wrote:
Here is a little trick to catch functions or methods that you haven't implemented yet. 

Interesting. Thanks for sharing this tip.

Edward
Reply all
Reply to author
Forward
0 new messages