hack to auto-define variables?

Andrew Dalke dalke at acm.org
Fri Oct 13 12:17:49 EDT 2000


Samuel A. Falvo II wrote:
[wants functionality like]
> >>> x
> *** Variable `x' implicitly declared in __main__, line ??
> None
[although for class instances.]

I don't understand the need for such a thing, except perhaps to
reduce a bit of typing.  For all such cases inside of an instance,
can't you use getattr(self, "x", None) instead?  It effectively
does what you want, and is even a bit better since you can replace
None with "" or 0.0 and specify the initial value.

>This way, during the course of running the application being developed, I
>can examine the log files to see if I need to do any source code cleanup.

I've worked on several projects where compiler warnings were simply
ignored.  In one such, over 1,000 were generated, and about a dozen of
them were real errors (most were about type casts and variables declared
but not used).  I'll wager that if this functionality is added, people
will ignore its output, or even complain about how it obscures running
code since they *know* it's correct.

With my workaround, you don't get see the output, making it somewhat more
difficult to see where you've added the interim code.  On the other hand,
"getattr(" is pretty rare code and easy to search for.  In addition, the
search can be done lexically, while for you case you would have to run
all the execution paths to ensure you aren't missing something.

Finally, you can have run-time output by writting your own variaion of
getattr:

  def my_getattr(obj, name, default = None):
      if hasattr(obj, name):
          return getattr(obj, name)
      # ... do the work to get the caller's filename line number
      # (try: "" except: "" ; back up a stack frame and get the
filename/lineno)
      # ... print the status information
      return default

You may also want a "setattr(obj, name, default) before the return.  In
which case, this function should be renamed to, perhaps, "setdefaultattr".

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list