[Tutor] Pythonic Style Question

Alan Gauld alan.gauld at yahoo.co.uk
Thu Jun 11 06:45:40 EDT 2020


On 11/06/2020 03:03, Richard Damon wrote:
> Long time programmer (started with punch cards)

You are not alone on this list, although in my case it was paper tape...

> Getting a lot of coding style errors for module global variables that
> seem to be a reasonable way to do it, but figured I would ask to see if
> there is a more Pythonic method to do these.

As an experienced programmer i'm sure you know why globals are generally
frowned on and the usual techniques for getting rid of them (pass as
function parameters return as values etc.)

> Example, application will have a number of settings stored in a
> configuration file, so I have a myconfig.py module that is called with
> the path to the config file, that uses configparser to read in the
> options and create a module global variable (config) that other parts of
> the system can import, and then query/set by accessing.

A lot depends on what kind of data you are storing but one common trick
for dealing with shared constants etc is to put them in a python module
and then import that module into every other module that requires
access. You can then edit the python module when you want to modify the
settings.

######## my_globals.py  #####
SIZE = 42
SCALE = 66
label = "My funky app"
#############################


##### Myapp.py  #####

import my_globals as globals


print (The size is: ", globals.SIZE)
globals.label = input("What label do you want? ")

etc...

Not sure if that helps at all but its something
that non-python programmers often overlook as
a possibility.

Obviously there are security/reliability issues in
allowing users to modify the code, but thats true
any time you ship source. If its on a server or other
secured location or its for your own use then it
should be OK.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list