Re: Modules aren't first-class values (was: New to Python: Features)
From: Tim Peters (tim.peters_at_gmail.com)
Date: Tue, 5 Oct 2004 16:26:38 -0400 To: email@example.com
>> 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
> 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
> 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
>>> import doctest # ditto name 'doctest'
>>> import new # you can even create module objects out of thin air
>>> print new.module.__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
>>> m = new.module('mymod')
>>> m.sin = math.sin
and so on.