class - distinct classes using `with` in Python -


if have following class:

class foo(object):      def __init__(name):         self.name = name 

and use in file called check_foo.py

with foo("naming it"):     print foo.name   foo("naming another"):     print foo.name 

if import check_foo , run dir(check_foo) single check_foo.foo module.

i know pep 343 mentions can like:

with foo("naming it") naming_it:     print naming_it.name 

and instantiated in check_foo check_foo.naming_it question is possible work around , set name dynamically.

i'm playing around proof of concept , want know how far can above idea.

could possible name instance using string passing foo ?

note: aware withhacks. let's not suggest take @ :)

i'm not sure if sort of hackery looking for...

import inspect  class renameable(object):   def rename_me(self, new_name):     stack_frame in inspect.stack()[1:]:       frame_object = stack_frame[0] # frame first object in tuple       (name, value) in frame_object.f_locals.iteritems():         if value 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 complete solution, allow change 1 binding of value name. changes name bound value closest call of rename_me. example:

>>> import blah >>> x = blah.renameable() >>> x <blah.renameable object @ 0x1004cb790> >>> x.rename_me('y') >>> x traceback (most recent call last):   file "<stdin>", line 1, in <module> nameerror: name 'x' not defined >>> y <blah.renameable object @ 0x1004cb790> >>> 

i'm not sure if better or worse using withhacks delve seldom explored module in library.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -