Reputation: 131
For example:
class Foo:
def __init__(self):
self.bar = "baz"
def test(self):
return "secret value that can only accessed in this function!!"
How can I do this:
x = Foo()
with x.test() as f:
print(f)
# "secret value that can only be accessed in this function!!"
Without raising an error?
Upvotes: 1
Views: 1717
Reputation: 1132
You should need a reason for using contextmanagers, but only as an example you could do something like this:
from contextlib import contextmanager
class Foo:
def __init__(self):
self.bar = "baz"
@contextmanager
def test(self):
print("doing something before entering `with block`")
yield "secret value that can only accessed in this function!!"
print("doing something else after exiting `with block`")
The usage will return:
x = Foo()
with x.test() as f:
print(f)
# "doing something before entering `with block`"
# "secret value that can only be accessed in this function!!"
# "doing something else after exiting `with block`"
More information at:
https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager
What is the python "with" statement designed for?
Upvotes: 2
Reputation: 1552
You can use contextlib.contextmanager
:
import contextlib
class Foo:
@contextlib.contextmanager
def bar(self):
yield 'secret'
and use it like so:
>>> x = Foo()
>>> with x.bar() as f:
... print(f)
secret
Note however that this is not sufficient to "hide" a variable from outside manipulation (so your secret will never be truly secret). Python is dynamic to the core, so most "security measures" rely on an unwritten convention that users do not try and actively circumvent them.
Upvotes: 3