Is there a way to enter an object's namespace so that I can use its methods as though they were global? I was thinking of something using the with statement.
class Bar():
def methodA(self):
# do stuff
def methodB(self):
# do more stuff
def __enter__(self):
# somehow enter object namespace / transfer methods into global namespace
def __exit__(self, *args):
# exit object namespace / get rid of globalized methods
foo = Bar()
with foo:
methodA() # all works fine
methodB()
methodA() # throws an error
This is just a thought, that might not work at all. Or maybe there's a solution without the with statement.
This answers the original question but I suggest don't use it .
Similar to the suggested way of wKavey .
But I'm not sure why I would want to do that. I would need to make sure that there is no variable methodA
in the global namespace.
class Bar():
def __init__(self, value=5):
self.value = value
def methodA(self):
return self.value
def methodB(self):
return -self.value
def __enter__(self):
global methodA
global methodB
methodA = self.methodA
methodB = self.methodB
def __exit__(self, *args):
global methodA
del methodA
global methodB
del methodB
pass
foo = Bar()
with foo:
print(methodA()) # all works fine
print(methodB())
methodA() # throws an error
You can probably use the techniques described here: Insert variable into global namespace from within a function?
I'd imagine it will require some bookkeeping in the __enter__
and __exit__
functions in order to clean up after itself. This isn't really something standard, so there my be some other foot-guns that I'm overlooking.
(oh. Maximilian Peters' answer is doing the same with slightly different syntax and was here first...)
nothing i'd recommend but you could do this (you get in trouble of course if there is already a methodA
in the global namespace):
class Bar():
def methodA(self):
print("methodA called")
def methodB(self):
print("methodB called")
def __enter__(self):
g = globals()
g["methodA"] = self.methodA
g["methodB"] = self.methodB
def __exit__(self, *args):
g = globals()
del g["methodA"]
del g["methodB"]
foo = Bar()
with foo:
methodA() # all works fine
methodB()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.