Need help with Python scoping rules

Hendrik van Rooyen hendrik at microcorp.co.za
Thu Aug 27 09:44:35 EDT 2009


On Thursday 27 August 2009 11:31:41 Steven D'Aprano wrote:
>
> What you are calculating might actually be quite complicated to enter as
> a literal. You might have something like:

8< ---------- Complicated Table Example -------------------------------

Me?  - never!  I am just an assembler programmer.  I would not touch a thing 
like that with a barge pole.  Unless of course, I have to.

> Clearly this is a made-up example, but the principle is sound. If Python
> can calculate values for you, why not let it do so? It is easier for you,
> easier to check that you've calculated them correctly, easier to debug
> and read, it makes the algorithm clearer (fewer "magic constants"). Yes,
> there is a run-time cost, but you only pay it once, when you import the
> module, and it's likely to be not that much more expensive than parsing
> the literals anyway.
>
> Of course, for something as big and complicated as the above table, I'd
> almost certainly put the code to calculate it in a function outside of
> the class, but that's a matter of style, and it will work to put it
> inside the class.

It is a hell of a thing if it needs recursion to calculate - If it was really 
that complex, I would calculate it, check it (if I can), document it and put 
it in a module of its own, with "This side up", "Fragile", and other warning 
stickers all over it.

- Hendrik




More information about the Python-list mailing list