[Python-Dev] Changing existing class instances

Tim Peters tim_one@email.msn.com
Thu, 20 Jan 2000 00:59:51 -0500


[Guido, on Andrew's idea for automagically updating
 classes]

> There might be another solution.  When you reload a module,
> the module object and its dictionary are reused.
>
> Perhaps class and function objects could similarly be
> reused?  It would mean that a class or def statement
> looks for an existing object with the same name and type,
> and overwrites that.  Voila, all references are
> automatically updated.

Too dangerous, I think.  While uncommon in general, I've certainly seen
(even written) functions that e.g. return a contained def or class.  The
intent in such cases is very much to create distinct defs or classes
(despite having the same names).  In this case I assume "the same name"
wouldn't *usually* be found, since the "contained def or class"'s name is
local to the containing function.  But if there ever happened to be a
module-level function or class of the same name, brrrr.

Modules differ because their namespace "search path" consists solely of the
more-global-than-global <wink> sys.modules.

> This is more work (e.g. for classes, a new bytecode may
> have to be invented because the class creation process
> must be done differently) but it's much less of a hack,
> and I think it would be more reliable. (Even though it
> alters borderline semantics a bit.)

How about an explicit function in the "new" module,

    new.update(class_or_def_old, class_or_def_new)

which overwrites old's guts with new's guts (in analogy with dict.update)?
Then no semantics change and you don't need new bytecodes.  In return, a
user who wants to e.g. replace an existing class C would need to do

    oldC = C
    do whatever they do to get the new C
    new.update(oldC, C)

Building on that, a short Python loop could do the magic for every class and
function in a module; and building on *that*, a short "updating import"
function could be written in Python.  View it as providing mechanism instead
of policy <0.9 wink>.

> (Your extra indirection also slows things down, although
> I don't know by how much -- not just the extra memory
> reference but also less locality of reference so more
> cache hits.)

Across the universe of all Python programs on all platforms, weighted by
importance, it was a slowdown of nearly 4.317%.

if-i-had-used-only-one-digit-everyone-would-have-
    known-i-was-making-it-up<wink>-ly y'rs  - tim