from... import...

Ben Finney bignose+hates-spam at benfinney.id.au
Sat Feb 3 00:24:54 EST 2007


fatwallet961 at yahoo.com writes:

> what's the from ... import keyword use for?
> for example - from contenttype import getContentType
>
> import os
> import sys
> import getopt
> import types
> import re
> import pprint
> import logging
> from contenttype import getContentType

The program now can access attributes as follows:

    foo = sys.argv[1]
    bar = logging.getLogger()
    baz = getContentType()

In other words, use 'from spam import eggs' when you want to refer to
'eggs' instead of 'spam.eggs'. In the specific case you cite, probably
the programmer knows they only want to access one attribute --
'getContentType' -- and would rather use that name for ease of reading
rather than the longer 'contenttype.getContentType'.

It's for this reason that many of the standard library modules have
relatively short names, eight characters or less. It has the result
that 'import spam' followed by access to 'spam.eggs' is both clear,
and easy enough to read.

To learn more, read about Python namespaces.

-- 
 \        "I bought a dog the other day. I named him Stay. It's fun to |
  `\     call him. 'Come here, Stay! Come here, Stay!' He went insane. |
_o__)      Now he just ignores me and keeps typing."  -- Steven Wright |
Ben Finney




More information about the Python-list mailing list