A proposal for attribute lookup failures

MonkeeSage MonkeeSage at gmail.com
Sun Nov 18 05:07:25 CET 2007


Proposal:

  When an attribute lookup fails for an object, check the top-level
(and local scope?) for a corresponding function or attribute and apply
it as the called attribute if found, drop through to the exception
otherwise. This is just syntactic sugar.


Example:

  a = [1,2,3]

  a.len()
  # -> fails,
  # -> finds len() in the top-level symbol table,
  # -> applies len(a)
  # -> 3

  a.foobar()
  # -> fails,
  # -> no foobar() in scope,
  # -> raise NameError


Benefits:

  - Uniform OO style. Top-levels can be hidden as attributes of data.
Most of the top-level functions / constructors can be considered as
attributes of the data; e.g., an int() representation of a string can
be considered as _part_ of the semantics of the string (i.e., one
_meaning_ of the string is an int representation); but doing it this
way saves from storing the int (etc) data as part of the actual
object. The trade-off is speed for space.

  - Ability to "add" attributes to built-in types (which is requested
all the time!!) without having to sub-class a built-in type and
initialize all instances as the sub-class. E.g., one can simply define
flub() in the top-level (local?) namespace, and then use "blah".flub()
as if the built-in str class provided flub().

  - Backwards compatible; one can use the top-level functions when
desired. No change to existing code required.

  - Seemingly trivial to implement (though I don't know much C). On
attribute lookup failure, simply iterate the symbol table looking for
a match, otherwise raise the exception (like current implementation).


Drawbacks:

  - Could hide the fact that an extra (On?) lookup on the symbol table
is necessary for attribute lookup failure. (Maybe there could be a
switch/pragma to enable (or disable) the functionality?)

  - As above, attribute lookup failure requires an extra lookup on the
symbol table, when normally it would fall through directly to
exception.

  - ???


Disclaimer:

  I realize that very often what seems good to me, ends up being half-
assed, backwards and generally bad. So I'd appreciate input on this
proposition. Don't take it that I think the idea is wonderful and am
trying to push it. I am just throwing it out there to see what may
become of it.

Regards,
Jordan



More information about the Python-list mailing list