Beautiful Python

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Dec 28 05:38:01 CET 2005


On Tue, 27 Dec 2005 21:35:46 -0600, news wrote:

>> Sometimes putting import statements at the beginning is not feasible
>> (i.e. only when some condition has been met), as importing has some
>> impact on program execution (importing executes code in imported
>> module). This does not resemble Java imports (I don't know Perl).
>> 
>> -- 
> Wow ?!   I've only started looking at python but that sounds like very
> dangerous programming !  Can you give an example.

Dangerous? Why? What's the worst that can happen in:

import parrot
...code...
import aardvark
...code...

that can't happen with this?

import parrot
import aardvark
...code...
...code...



> BTW this topic relates to a recent point raised by the C man's
> [I think Richie, dated ca. 1973] crit of Pascal. He said that
> Pascal's restriction of not being able to declare globals, near
> where they were needed, was bad.  And I thought so too, before I
> considered that the programmer must KNOW that they are global.
> Ie. the ability to declare them at a 'nice' place is just syntactic
> sugar, hiding the reality the globals are bad, and have to be avoided
> and respected.

But Pascal still allows you to use globals.

"Avoid globals" is excellent advise and a good guideline, but if you want
a Bondage and Domination language that prohibits them, Python is not the
language for you.

Look at it this way: the Python interactive interpreter is perhaps the
single most useful feature of Python. You want to be able to use import in
interactive sessions, right? You want to be able to do this:

py> x = 32.2/4.5
py> math.log(x)  # oops, forgot to import math first...
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'math' is not defined
py> import math
py> math.log(x)
1.9678890557740887

without having to exit the session, restart, and import everything you
think you might need.

So Python has to allow imports in the middle of code. So why enforce the
guideline "all imports at the beginning of a module or script"? A module
is just another object in Python, why treat it differently from other
objects?



-- 
Steven.




More information about the Python-list mailing list