[Tutor] global variables/constants versus volatile variables/constants
Cameron Simpson
cs at zip.com.au
Sat Jun 14 07:35:52 CEST 2014
On 14Jun2014 11:21, Steven D'Aprano <steve at pearwood.info> wrote:
>On Fri, Jun 13, 2014 at 09:42:34PM +0530, diliup gabadamudalige wrote:
>> 2. Lists that are read only are better off being tuples?
>
>Possibly. It depends.
>
>As a general rule, tuples may be used for heterogeneous data, lists
>should be used for homogeneous data.
To make this less clear, I would say this is a useful rule some of the time. It
certainly isn't the only criterion one might use for choosing between a tuple
and a list.
>What do I mean by this?
>
>This is a good use for a tuple:
> customer = (name, address, phone_number, status, balance)
>
>You have a fixed number of fields, and each field means something
>different (they are hetrogeneous). You should not use a list for
>something like this.
Were I using the "heterogeneous data" rule I would be advocaing going to whole
hog and using a "namedtuple" from the "collections" module. This has the
advantage of giving each element of the tuple a nice name so that you can refer
to "customer.address" instead of using magic indices like "customer[1]". That
makes the code easier to read and easier to write.
But if you're not using namedtuple-like attributes to access the tuple
elements, then I would not be considering the "heterogeneous data" rule to be
as relevant in my choice of tuple or list.
There are some advantages to using a tuple as a frozen list, which can't have
its values modified nor have its size changed. Specificly, if that is your
intent and your code later tried to change the values (because it is buggy)
then Python will raise an exception immediately, making it easier to find your
mistake. If you stick to a list for this situation then the buggy changes will
go ahead and the error will only be apparent much later when you get the wrong
results.
Fail early, fail often!
Conversely, there are downsides to using tuples as frozen lists. The most
obvious is that you can't add lists and tuples together, just lists and lists.
If you need to add tuples and lists all the time then the surround fiddliness
required may be enough to push you back to using lists throughout.
Finally, another argument against mixing tuples and lists is simply that it may
be early optimisation. Unless you're benefiting from the "you can't
accidentally modify a tuple later" effect, just write it all with lists; it
will be simpler. You can always come back later after the code is functioning
correctly and think about tuples.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list