3

Is there a way to limit a function to be called by specific function(s)?

def a():
    private() # okay

def b():
    private() # raises error

def private():
    print "private"
Derek
  • 11,980
  • 26
  • 103
  • 162
  • 4
    If you're going to do that, why don't you just put the code of `private` directly inside `a`? – BrenBarn May 31 '13 at 04:49
  • 1
    Not without some terrible `inspect` gymnastics. Why do you want this? Why not just call the function where you need to call it, and not where you don't? – Henry Keiter May 31 '13 at 04:53
  • in my code the functions are object methods, it's more organized when they're separate, and I also might want def c() to call private(). – Derek May 31 '13 at 04:53
  • I would imagine you could use this http://stackoverflow.com/questions/2654113/python-how-to-get-the-callers-method-name-in-the-called-method inside private() to filter out the functions that shouldn't be allowed to call it. EDIT: looks like Henry beat me to it. – Kyle G. May 31 '13 at 04:53

1 Answers1

3
import inspect
def private():
    cframe = inspect.currentframe()
    func = inspect.getframeinfo(cframe.f_back).function
    if func != 'a':
        print 'not allowed from ', func
    print "private"
perreal
  • 94,503
  • 21
  • 155
  • 181