Skip to content Skip to sidebar Skip to footer

Limit A Method To Be Called Only Through Another Method?

Say i have two methods first_method and second_method as follows. def first_method(some_arg): ''' This is the method that calls the second_method ''' return second

Solution 1:

Why don't you define the second method within first method, so that its not exposed to be called directly.

example:

deffirst_method(some_arg):
    """
    This is the method that calls the second_method
    """defsecond_method(arg1, arg2):
        """
        This method can only be called from the first_method
        hence defined here
        """#Execute the second_methodreturn second_method(some_arg[1], some_arg[2])

Solution 2:

You could look at some of the stack functions in the inspect module.

However, what you are doing is probably a bad idea. It simply isn't worth the trouble to try to enforce this sort of thing. Just document that the second method is not supposed to be called directly, give it a name with a leading underscore (_secret_second_method or whatever), and then if anyone calls it directly it's their own problem.

Alternatively, just don't make it a separate method and put the code right in first_method. Why do you need to make it a separate function if it's never called except from one place? In that case it might as well be part of the first method.

Solution 3:

Here is example, not particularly related to Django, of how to obtain caller method frame (there is a lot of info in that frame):

import re, sys, thread

defs(string):
    ifisinstance(string, unicode):
        t = strelse:
        t = unicode
    defsubst_variable(mo):
        name = mo.group(0)[2:-1]
        frame = sys._current_frames()[thread.get_ident()].f_back.f_back.f_back
        if name in frame.f_locals:
            value = t(frame.f_locals[name])
        elif name in frame.f_globals:
            value = t(frame.f_globals[name])
        else:
            raise StandardError('Unknown variable %s' % name)
        return value
    return re.sub('(#\{[a-zA-Z_][a-zA-Z0-9]*\})', subst_variable, string)

first = 'a'
second = 'b'print s(u'My name is #{first} #{second}')

Basically you may use sys._current_frames()[thread.get_ident()] to obtain head of frame linked list (frame per caller) and then lookup for whatever runtime info you want.

Post a Comment for "Limit A Method To Be Called Only Through Another Method?"