[Tutor] global variables/constants versus volatile variables/constants

Alan Gauld alan.gauld at btinternet.com
Fri Jun 13 09:55:54 CEST 2014


On 13/06/14 08:21, diliup gabadamudalige wrote:

> In my code there are many dictionaries and lists which are used in
> various functions. Is it better/pythonic/efficient to have these inside
> the function itself or declared at the beginning of the program in which
> case they will be global?

If you are sharing a set of data structures between several functions 
thats often a sign they should be in a class. The data then becomes the 
class instance attributes and the functions become the methods.

> global constants and variable have memory allocated to them but when
> declared inside a function are created on the fly, used and discarded.

That's not usually the main issue when deciding for global/local.
Its more about the maintainability of the code and the over
use of side effects which makes the code difficult to read.
If the data is read only then things are not so bad and globals
can be an OK solution.

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list