Efficiency/style issues of import <module> vs. from <module> import <name>, ...

Stephen Hansen me+list/python at ixokai.io
Thu Jun 17 13:40:19 EDT 2010


On 6/17/10 10:22 AM, Jack Diederich wrote:
> On Thu, Jun 17, 2010 at 12:58 PM, Stephen Hansen
>> It explicitly states later its entirely OK to import classes. It never
>> says anything else directly, except in the example given, it shows you
>> importing a constant. So, its giving implicit approval to that without
>> really directly saying anything about it.
> 
> You want to import a name that is itself a namespace; preferably a
> module or package and sometimes a class.  Importing constants can lead
> to trouble.  ex/
> 
> from settings import DEBUG
> if DEBUG: log('debug is on!')
> 
> The value of the flag gets fetched at import time.  If code in another
> module updates settings.DEBUG later your module won't see it. ditto
> for exceptions.

That argument is invalid on its face; a constant, by definition, is not
to be modified. The convention (recently adopted officially by PEP-8) of
ALL_CAPS makes this promise: this is a static piece of data.

That its possible for misbehaving code to change it due to Python's lax
nature doesn't mean you should organize or write your code in such a way
to take that into account. People can shoot themselves in the foot.

If people do stupid things after writing code that makes promises, stuff
that relies upon the explicit promises made may fail, and that's their
own dumb fault.

And the only time someone is going to go 'change' an exception that
lives in the top-level of some other module is if they're
monkey-patching, which while a legitimate technique to achieve certain
ends when using other people's code-- is also not a technique which has
any place in consideration of the design phase of the original system
itself.

Certainly, importing a non-constant immutable piece of data is
problematic in theory, as it can be rebound and problems arise.

Number of times I've -seen- non-constant immutable data in the top-level
of a module: 0*.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

P.S. Outside of a throw-away script which is not meant to be imported,
at least.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100617/35e82480/attachment.sig>


More information about the Python-list mailing list