Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a static utility class correctly in Python

Tags:

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()

Upon execution this throws the error.

NameError: global name 'configParser' is not defined

Why is python not able to recognize the static member.

like image 245
station Avatar asked Jun 13 '26 11:06

station


1 Answers

In general, it is almost always better to use @classmethod over @staticmethod.

Then, configParser is an attribute of the cls argument:

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 your usage of self is replaced by cls.

like image 179
shx2 Avatar answered Jun 15 '26 01:06

shx2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!