(original) (raw)



On 3/14/07, Neal Norwitz <nnorwitz@gmail.com> wrote:

---------- Forwarded message from python-3000-checkins ----------

Neal Norwitz schrieb:
> I assume this is not the desired behaviour?
>
>>>> class F:
> ...   def __dir__(self):
> ...     return [5]

> ...
>>>> dir(F())
> [5]
>>>> f = F()
>>>> dir(f)
> [5]
>>>> def __dir__(): return [10]
> ...
>>>> f.__dir__ = __dir__

>>>> dir(f)
> [5]
>
> I think the problem is in _dir_object()
>
> +       PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type,
> +                                                   "__dir__");

>
> Shouldn't the first arg just be obj, not obj->ob_type?

[Georg]
This is modeled after the principle that for new-style objects, __special__
methods are looked up on the type, not the instance.


-----

1) I didn't remember this, do we have it documented somewhere?
2) Assuming #1 is correct, is this rule consistently applied?
3) How does (should) this affect 2.6 and migration to 3.0, if at all?


I don't remember seeing it documented, but it's the biggest (and hardest to detect) incompatibility between classic and new-style classes. It does, however, make sense to me. (The type is what defines behaviour, not the instance.) It seems to be quite consistently applied throughout the interpreter, but not throughout other modules that use their own \_\_hooks\_\_ -- say, pickle. That's because they (naturally) do 'obj.\_\_hook\_\_()', not 'obj.\_\_class\_\_.\_\_hook\_\_(obj)'. We could make this entirely consistent by making all \_\_\*\_\_ methods be data descriptors on the class, which takes precedence over instance attributes. (So make them like property() rather than methods like now; you wouldn't be able to shadow them in an instance's \_\_dict\_\_.) A decorator would make sense too if we controlled all places the hooks get defined, but we don't, so it doesn't.

As for 2.6->3.0 migration, it's all part of classic vs. new-style, but yes, we should warn about this. And yes, we can, although only by somewhat evil magic: make a list of affected \_\_methods\_\_ (unless we're going to solve it generically like I sketched above, which I doubt), make a special data descriptor on classic instances for each one, have that data descriptor check to see if the instance has a shadowing attribute in \_\_dict\_\_ and if so, warn and use it.

n
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
Python-3000 mailing list
Python-3000@python.org
http://mail.python.org/mailman/listinfo/python-3000
Unsubscribe: http://mail.python.org/mailman/options/python-3000/thomas%40python.org



--
Thomas Wouters <thomas@python.org>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!