[Python-ideas] Classes inside functions [was Re: Add __parent__ to all classes, functions, and modules]
Steven D'Aprano
steve at pearwood.info
Mon Oct 6 04:36:29 CEST 2014
On Sun, Oct 05, 2014 at 02:43:13PM -0700, Guido van Rossum wrote:
> An alternative that wouldn't even require a metaclass would be to write a
> helper function that looks the class object up by name after parsing
> __qualname__. There are some limitations to this, e.g. classes defined
> inside functions -- but that's already a suspect pattern anyway.
I understand that "suspect pattern" doesn't mean "don't ever do this",
but I wonder what aspect of defining classes inside a function is
suspect. I think the suspect part is that each invocation of the
function creates a new class which (at least in the naive case) has the
same name, same functionality, and looks identical to the casual
glance but actually isn't. So given:
def maker():
class MyClass: pass
return MyClass
x = maker()()
y = maker()()
assert isinstance(x, type(y))
assert isinstance(y, type(x))
both assertions will fail, which may confuse some people. There's
probably also implications for pickling as well. Are these the only
"suspect" parts of defining classes inside functions, or have I missed
something else?
--
Steven
More information about the Python-ideas
mailing list