[Python-Dev] Metaclass problem in the "with" statement semantics in PEP 343

Guido van Rossum guido at python.org
Mon Nov 28 17:24:08 CET 2005

On 11/28/05, Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> Given the current semantics of PEP 343 and the following class:
>    class null_context(object):
>      def __context__(self):
>          return self
>      def __enter__(self):
>          return self
>      def __exit__(self, *exc_info):
>          pass
> Mistakenly writing:
>     with null_context:
>         # Oops, passed the class instead of an instance
> Would give a less than meaningful error message:
>      TypeError: unbound method __context__() must be called with null_context
> instance as first argument (got nothing instead)
> It's the usual metaclass problem with invoking a slot (or slot equivalent) via
> "obj.__slot__()" rather than via "type(obj).__slot__(obj)" the way the
> underlying C code does.
> I think we need to fix the proposed semantics so that they access the slots
> via the type, rather than directly through the instance. Otherwise the slots
> for the with statement will behave strangely when compared to the slots for
> other magic methods.

Maybe it's because I'm just an old fart, but I can't make myself care
about this. The code is broken. You get an error message. It even has
the correct exception (TypeError). In this particular case the error
message isn't that great -- well, the same is true in many other cases
(like whenever the invocation is a method call from Python code).

That most built-in operations produce a different error message
doesn't mean we have to make *all* built-in operations use the same
approach. I fail to see the value of the consistency you're calling

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list