hack to auto-define variables?
Michal Wallace
sabren at manifestation.com
Thu Oct 5 20:51:14 EDT 2000
I'm trying to come up with a way to make something like this happen:
>>> x
None
WITHOUT saying "x=None":
>>> x = "blablalskdjflaskdjf"
>>> del x
>>> x
None
Bascially, I'd like to make variables just pop into existence under
certain circumstances.
My first thought was to replace __dict__ (or __dict__.__getitem__) but
this raises an error.
Then I thought maybe I could throw an exception, assign the variable,
and then find some way to make that exception disappear.. (Like
whoever mentioned signals vs exceptions earlier).. But I haven't
found a way to make that happen.
Then I found a way I could do what I wanted for a module that I'm
importing, but not the top level module:
## a module that isn't a module....
## must call with "from badboy import *" though.. :/
class _BadBoy:
def __init__(self):
self.__dict__["__attrs__"] = {}
self.__dict__["__default__"] = None
def __getattr__(self, name):
return self.__dict__["__attrs__"].get(
name, self.__dict__["__default__"])
def __setattr__(self, name, value):
self.__dict__["__attrs__"][name] = value
def __str__(self):
return "BADBOY!"
try:
raise "this is just a hack!"
except:
_frame = sys.exc_info()[2].tb_frame.f_back
_frame.f_locals["badboy"] = _BadBoy()
#####
>>> from badboy import * # because import is an assignment
>>> badboy.name
None
#####
I've got some other ideas, but they all seem like too much work:
- write a C module that, when you import it, replaces the locals()
of the calling frame with something that has a __getitem__..
- write a wrapper script, and just define my own __globals__..
maybe give scripts like this a special extension, and create
an ihook...
- preprocess the python file and define variables myself..
- hack python itself, and make __dict__ writable..
- set sys.settrace() to some evil function that will look
ahead for uses of undeclared variables and declare them
before they cause an error.. (Which sounds like a lot of
fun, but I suspect it would kill performance)
- some kind of bytecodehack?
Anyone have any ideas? (besides "just declare your variables!")
Cheers,
- Michal
------------------------------------------------------------------------
www.manifestation.com www.sabren.com www.linkwatcher.com www.zike.net
------------------------------------------------------------------------
More information about the Python-list
mailing list