Defining scope / context of a method call in python

I would like to write a decorator for a python class method that can determine if a method is called from a public context or a private context. For example, given the following code

def public_check_decorator(f):
    def wrapper(self):
        if self.f is `called publicly`:  # <-- how do I make this line work correctly?
            print 'called publicly'
        else:
            print 'called privately'
        return f(self)
    return wrapper

class C(object):
    @public_check_decorator
    def public_method(self):
        pass

    def calls_public_method(self):
        self.public_method()

Executing an execution would ideally look something like this:

>>> c = C()
>>> c.public_method()
called publicly

>>> c.calls_public_method()
called privately

Is there any way to do this in python? That is, change the line

if self.f is `called publicly`:  # <-- how do I make this line work correctly?

to give the desired result?

+4
source share
2 answers

Some of them seem to be trying to cross the python stream. It is suitable?

Do you know the double shard standard? This makes the methods "more private":

>>> class C(object):
...    def __hide_me(self):
...        return 11
...    def public(self):
...        return self.__hide_me()
...
>>> c = C()
>>> c.__hide_me()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute '__hide_me'
>>> c.public()
11
>>> c._C__hide_me()
11
>>>

? .

0

, , :

import inspect
import re


def run():
    package_name = '/my_package/'
    p = re.match(r'^.*' + package_name, inspect.stack()[0].filename).group()
    is_private_call = any(re.match(p, frame.filename) is not None for frame in inspect.stack()[1:])
    print(is_private_call)

, !!! . inspect.stack()

0

Source: https://habr.com/ru/post/1525550/


All Articles