Module-level functions and the module type

Chris Kaynor ckaynor at zindagigames.com
Mon Aug 18 12:53:23 EDT 2014


On Sun, Aug 17, 2014 at 8:15 AM, Chris Angelico <rosuav at gmail.com> wrote:

> In a class definition, you have explicit state parameters on your
> functions - 'self':
>
> class C:
>     def foo(self, arg):
>         # blah blah
>
> At module level, there's equivalent state - the function "knows" what
> module it came from - but it's implicit:
>
> def foo(arg):
>     # blah blah
>
> print(foo.__globals__)
>
> How hard would it be to unify these, and make modules into classes?
> This would then allow stuff like properties, metaclasses, and so on,
> all with exactly the same semantics as they have in classes.
>
> Obviously this would be a huge backward-compatibility break if it
> happened everywhere, but what I'm looking at here is a way to
> basically bless this kind of concept:
>
> # spam.py
> class RealSpam:
>     # module contents here
>
> import sys
> sys.modules[__name__] = RealSpam()


> So the question is: Why is state implicit in one and explicit in the
> other? Which option is really the better way to do things?
>

As a heads up, we did this at work (mostly, just to support module-level
properties) by using an import hook to adjust the type of object loaded
from .py files. At the root, it was fairly easy to implement (though quite
a bit of boiler code), however the main problem we ran into was performance
- doing so slowed down all module accesses.

The other issue with the way we did it (we didn't pass in the module to all
functions) was that global accesses would not access the properties, so
work-arounds had to be done to access them within the module itself.

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140818/7284d66a/attachment.html>


More information about the Python-list mailing list