How to correctly define a static utility class in Python

I wanted to write a utility class to read from a config file in python.

import os,ConfigParser

class WebPageTestConfigUtils:

    configParser = ConfigParser.RawConfigParser()
    configFilePath = (os.path.join(os.getcwd(),'webPageTestConfig.cfg'))

    @staticmethod
    def initializeConfig():
        configParser.read(self.configFilePath)

    @staticmethod
    def getConfigValue(key):
        return configParser.get('WPTConfig', key)

def main():
    WebPageTestConfigUtils.initializeConfig()
    print WebPageTestConfigUtils.getConfigValue('testStatus')

if  __name__ =='__main__':
    main()

      

This throws an error when executed.

NameError: global name 'configParser' is not defined

Why can't python recognize static member.

+3


source to share


3 answers


In general, it is almost always best to use @classmethod

over @staticmethod

.

Then configParser

is an attribute of the argument cls

:



class WebPageTestConfigUtils(object):

    configParser = ConfigParser.RawConfigParser()
    configFilePath = (os.path.join(os.getcwd(),'webPageTestConfig.cfg'))

    @classmethod
    def initializeConfig(cls):
        cls.configParser.read(cls.configFilePath)

    @classmethod
    def getConfigValue(cls, key):
        return cls.configParser.get('WPTConfig', key)

      

Also note that your usage self

is being replaced by cls

.

+2


source


Class and instance attributes are not involved in the process of resolving variables within a method. If you want to access them, you need to use the normal attribute lookup syntax:

WebPageTestConfigUtils.configParser.read(self.configFilePath)

      



However, you shouldn't use a class for this. You seem to be used to the language where everything should be in the classroom. Python doesn't work this way; you should just use a module with normal functions in it.

+1


source


If you want to create static variable in your file, create before class definition. Usually in a static variable python is declared as UPPERCASE variable name.

As an example, you can use

CONFIGPARSER = ConfigParser.RawConfigParser()
CONFIGFILEPATH = (os.path.join(os.getcwd(),'webPageTestConfig.cfg'))

...
...
@staticmethod
def initializeConfig():
    CONFIGPARSER.read(CONFIGFILEPATH)
...
...

      

0


source







All Articles