distinct classes using `with` in Python
If you have the following class:
class Foo(object):
def __init__(name):
self.name = name
And you use it like this in a file called check_foo.py
with Foo("naming it"):
print Foo.name
with Foo("naming another"):
print Foo.name
If you import check_foo
and run dir(check_foo)
you will only get a single check_foo.Foo
module.
I know that PEP 343 mentions that you can d开发者_StackOverflow中文版o something like:
with Foo("naming it") as naming_it:
print naming_it.name
And that it would get instantiated properly in check_foo
as check_foo.naming_it
but my question is it is possible to work around this and set the name dynamically.
I'm playing around with a proof of concept and want to know how far I can get with the above idea.
Could it be possible to name the instance using the string I am passing to Foo
?
Note: I am also aware about withhacks
. Let's not suggest I take a look at that :)
I'm not sure if this is the sort of hackery that you are looking for...
import inspect
class renameable(object):
def rename_me(self, new_name):
for stack_frame in inspect.stack()[1:]:
frame_object = stack_frame[0] # frame is the first object in the tuple
for (name, value) in frame_object.f_locals.iteritems():
if value is self:
old_name = name
matched_frame = frame_object
break
if matched_frame:
break
if matched_frame:
matched_frame.f_locals[new_name] = matched_frame.f_locals[old_name]
del matched_frame.f_locals[old_name]
I doubt that this is a complete solution, but it does allow you to change one binding of a value to a name. It changes the name that is bound to the value which is closest to the call of rename_me
. For example:
>>> import blah
>>> x = blah.renameable()
>>> x
<blah.renameable object at 0x1004cb790>
>>> x.rename_me('y')
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> y
<blah.renameable object at 0x1004cb790>
>>>
I'm not sure if this is better or worse than using withhacks
but it does delve into a seldom explored module in the library.
精彩评论