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 do 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…
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:I’m not sure if this is better or worse than using
withhacksbut it does delve into a seldom explored module in the library.