The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

Steven D'Aprano steve at pearwood.info
Sat Mar 12 21:01:50 EST 2016


On Sun, 13 Mar 2016 10:57 am, BartC wrote:

> I use 'const' everywhere in other languages, most often in the form of
> sophisticated sets of enums. A single project might have 1000 or even
> 2000. (Example that defines a set of byte-codes:
> http://pastebin.com/q1UwjKmK)
> 
> How does Python manage without them? Is it really necessary to declare
> hundreds of individual variables and assign a value to each? (And risk
> someone assigning a new value to them.)

Copying from your code, you define a bunch of constants in a table (many of
which apparently have the same value?):

global tabledata()  cmdnames, cmdfmt =
   (kzero=0,       $,  (0,0,0,0)),
   (knop,          $,  (0,0,0,0)),
   (klabel,        $,  (l,0,0,0)),
   (kcodestart,    $,  (p,h,0,0)),
   (kcodeend,      $,  (0,0,0,0)),
   (kendmodule,    $,  (0,0,0,0)),
   (kendprogram,   $,  (0,0,0,0)),
   ...
end

I don't understand the syntax. You seem to have three columns in the table,
a name, a $ whatever that is for, and some data (four values in a
comma-separated parenthesised list), but the table appears to only define
two columns (cmdnames, cmdfmt). Mysterious.

In Python, we might similarly define a table, using a dict:

tabledata = dict(
    kzero=(0,0,0,0),
    knop=(0,0,0,0)),
    klabel=(l,0,0,0)),
    kcodestart=(p,h,0,0)),
    kcodeend=(0,0,0,0)),
    kendmodule=(0,0,0,0)),
    kendprogram=(0,0,0,0)),
    ...
    )


So the amount of typing is comparable. If you have 200 symbolic names with
associated data, one way or the other you have to enter 200 symbolic names
and their associated data into your source code, regardless of whether they
are called "constants", "enums", "variables" or "symbols".

The dict solution does have the rather sad consequence that we then have to
use quoted names for the symbols:

x = tabledata['klabel']

although one can make a simple wrapper around the dict to fix this:

class table:
    pass

table.__dict__ = tabledata

x = table.klabel


And if you want to make these "constants" available as top-level names as
well as via the table:

globals.update(tabledata)

What about the risk that somebody might modify them? The Pythonic answer
is "well don't do that". The names are clearly marked with a leading "k"
for "konstant", so unless documented otherwise they're not variables. We
don't need the compiler to enforce that rule.

Some of us might like a more traditional rule.



-- 
Steven




More information about the Python-list mailing list