[Tutor] Pythonic Style Question

Peter Otten __peter__ at web.de
Thu Jun 11 06:28:22 EDT 2020


Richard Damon wrote:

> Background:
> 
> Long time programmer (started with punch cards) but fairly new to punch
> cards, but fairly new to Python.
> 
> Working on a program that will be a moderate size program when done, and
> doing it in Python as it looks to be a reasonable choice, and a good
> learning experience.
> 
> Decided to try running pylint on it to see what sort or 'Preferred
> Style' it would lead me to (might as well have something look over the
> code and critique it) (I know the weaknesses of Linters, but worth a shot)
> 
> 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.
> 
> 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.

Do you use the global statement to rebind the global `config` name

def read_config()
    global config
    config = ...
read_config()

or to modify it

def update_config():
    global config
    config.working_directory = ...

? In the second example `global` is unnecessary, in the first you might at 
least consider changing it to

def read_config():
    config = ...
    return config
config = read_config()

> pylint first complains that these 'constants' should be in ALL_CAPS (but
> they aren't constants, so I don't think they should be ALL_CAPS),

I think that's indeed very annoying. I sometimes ignore it and sometimes 
tinker with the config file's const-rgx.

If I understand

http://pylint.pycqa.org/en/latest/whatsnew/2.5.html

correctly the situation may have improved.

> and in
> the function that will set it up, complains of the global statement so
> it can access the module global. I could also create my own access
> wrappers to get/set options, that other modules will call, but I would
> think I would still need the module global (and making it _config to
> mark it as a non-global still gets all the warnings about the constant
> not being ALL_CAPS).
> 
> Is there another better way to do this sort of thing? or is pylint just
> being over picky (as lints are prone to be) and I need to put a comment
> on the statement to tell pylint it is ok?

Having as few global variables as possible (but not fewer) seems a good idea 
to me.




More information about the Tutor mailing list