Modules aren't first-class values (was: New to Python: Features)

Tim Peters tim.peters at gmail.com
Tue Oct 5 16:26:38 EDT 2004


[Richard Blackwood]
>> But modules for example, the docs don't tell me at all that I can use
>> modules as variables and that I can pass them into and out of
>> functions/methods.

[Cameron Laird]
> I've seen you assert this a couple of times.  I haven't been
> able to spot the revelation in this thread which inspired you
> to it.

Someone said so, in reply.

> I suspect there's a confusion somewhere.  Modules
> are *not* first-class values,

Of course they are:  a module is a Python object, and is as
"first-class" as an integer, function, file, ..., or any other kind of
Python object.

> although their names are.

I don't know what that means.

> It sounds as though the standard documentation lacks something
> in regard to modules, but I don't know what it is.

All Python objects can be passed to functions, returned from
functions, stored as values in lists and dicts, etc.  The Python docs
don't explicitly say that all over again for each object type, though
-- it's universally true.

>>> import math
>>> type(math)  # name 'math' is bound to a module object
<type 'module'>
>>> import doctest  # ditto name 'doctest'
>>> type(doctest)
<type 'module'>
>>> import new   # you can even create module objects out of thin air
>>> print new.module.__doc__
module(name[, doc])

Create a module object.
The name must be a string; the optional doc argument can have any type.
>>> def getsin(mod):   # a function taking a module object as argument
...     return mod.sin
>>> doctest = math  # silly but legitimate
>>> getsin(doctest)(3.14)
0.0015926529164868282
>>> m = new.module('mymod')
>>> m.__name__
'mymod'
>>> m.sin = math.sin
>>> getsin(m)(3.14)
0.0015926529164868282

and so on.



More information about the Python-list mailing list