[Tutor] factorial
Jeff Shannon
jeff@ccvcorp.com
Mon May 12 13:43:03 2003
Greg Chapman wrote:
>>I wish [...] to be able to edit script and go right
>>
>>
>>back in and run without having to close the dos >>> box and re-enter and
>>then from factorial import
>>* . should be able to from factorial import * without closing the >>>
>>session.
>>
>>
>
>you should be able to do: >>>reload(factorial)
>
>
Actually, given the use of 'from X import *', that won't work, which is
just one of *many* reasons to avoid using that style of import.
If you simply use 'import factorial', and then refer to the functions as
factorial.fact(), factorial.fact2(), etc, then you should be able to
reload(factorial) and have any changes to the module become effective
within the current Python session.
For another reason to avoid using 'from X import *', consider the following:
>>> print pow.__doc__
pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
>>> import math
>>> print math.pow.__doc__
pow(x,y)
Return x**y (x to the power of y).
>>>
So there's a built-in pow() function and a math.pow() function, with
slightly different semantics. Now, given Cino's usage, the factorial
module uses 'import *' to bring all of the math module's names into its
namespace, and then in an interactive session brings all of the
factorial module's names (which now includes all of the math module's
names) into the global namespace. So now math.pow() has been brought
into factorial which has been brought into global... and now pow() will
refer to math.pow() and not the built-in (three argument) pow(). If you
later use pow() with three arguments, expecting to get the built-in
version, you'll get an error, and you'll probably have no idea why.
This is another one of those "enough rope to hang yourself" features,
along with exec/eval(), that might *seem* to make things easier at first
but are really best left for special circumstances. The power they give
you can be useful, but it can also be dangerous, and it's best to avoid
them unless you're really sure that it's the best/only solution to the
problem.
Jeff Shannon
Technician/Programmer
Credit International