module confusion
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Oct 3 07:12:13 EDT 2007
En Wed, 03 Oct 2007 07:12:17 -0300, Lawrence D'Oliveiro
<ldo at geek-central.gen.new_zealand> escribi�:
> In message <mailman.1404.1191345163.2658.python-list at python.org>, Robert
> Kern wrote:
>
>> Lawrence D'Oliveiro wrote:
>>
>>> In message <mailman.1379.1191301581.2658.python-list at python.org>,
>>> Robert
>>> Kern wrote:
>>>
>>>> Not all of the modules in a package are imported by importing the
>>>> top-level package.
>>>
>>> You can't import packages, only modules.
>>>
>>>> os.path is a particularly weird case because it is just an alias to
>>>> the
>>>> platform-specific path-handling module; os is not a package.
>>>
>>> os is a module, os.path is a variable within that module. That's all
>>> there is to it.
>>
>> Yes, but os.path is also module. That's why I said it was a weird case.
>
> You can't have modules within modules. os.path isn't an exception--see
> below.
>
>> In [1]: import os
>>
>> In [2]: type(os.path)
>> Out[2]: <type 'module'>
>
> On my Gentoo system:
>
> >>> import os
> >>> os.path
> <module 'posixpath' from '/usr/lib64/python2.5/posixpath.pyc'>
>
> It's just a variable that happens to point to the posixpath module.
A "module" is a certain type of Python objects, like ints, functions,
exceptions and all else.
The easiest way to create a module is to load it from file, but some
modules are already built into the interpreter, and you can even create a
module from scratch.
py> import os
py> type(os)
<type 'module'>
py> type(os.path)
<type 'module'>
py> os
<module 'os' from 'c:\apps\python25\lib\os.pyc'>
py> import sys
py> type(sys)
<type 'module'>
py> sys
<module 'sys' (built-in)>
py> ModuleType = type(os)
py> newmodule = ModuleType('newmodule')
py> newmodule.a = 3
py> newmodule
<module 'newmodule' (built-in)>
py> type(newmodule) is type(os.path)
True
"os" is a name that refers to the os module object. "os.path" means "the
path attribute in the object referenced by the name os", that happens to
be another module too.
os is not a package; os.path is set when the os module is imported,
depending on the platform. It may be ntpath, posixpath, macpath, or
whatever. On Windows:
py> import ntpath
py> os.path is ntpath
True
py> import macpath
py> import posixpath
py> macpath.sep
':'
py> ntpath.sep
'\\'
Apart from that, there is no magic involved, just plain attribute access
like everywhere else.
--
Gabriel Genellina
More information about the Python-list
mailing list