Last active
May 30, 2018 08:26
-
-
Save jnrbsn/7573114 to your computer and use it in GitHub Desktop.
Python decorator for making an instance method private
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
def privatemethod(func): | |
"""decorator for making an instance method private""" | |
def func_wrapper(*args, **kwargs): | |
"""decorator wrapper function""" | |
outer_frame = inspect.stack()[1][0] | |
if 'self' not in outer_frame.f_locals or outer_frame.f_locals['self'] is not args[0]: | |
raise Exception('%s.%s is a private method' % (args[0].__class__.__name__, func.__name__)) | |
func(*args, **kwargs) | |
return func_wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment