Limit a method to be called only through another method?

耗尽温柔 提交于 2019-12-13 02:43:50

问题


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_method(some_arg[1], some_arg[2])


def second_method(arg1, arg2):
    """
    This method can only be called from the first_method
    or it will raise an error.
    """

    if (some condition):
        #Execute the second_method
    else:
        raise SomeError("You are not authorized to call me!")

How can i check (what condition(s)) that second method is being called by the first method and process the method according to that ?


回答1:


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.




回答2:


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

example:

def first_method(some_arg):
    """
    This is the method that calls the second_method
    """
    def second_method(arg1, arg2):
        """
        This method can only be called from the first_method
        hence defined here
        """

        #Execute the second_method


    return second_method(some_arg[1], some_arg[2])



回答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

def s(string):
    if isinstance(string, unicode):
        t = str
    else:
        t = unicode
    def subst_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.



来源:https://stackoverflow.com/questions/13984818/limit-a-method-to-be-called-only-through-another-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!