3

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.

station
  • 6,715
  • 14
  • 55
  • 89
  • 3
    Python is not Java, normally you use a class just if it's something you are going to instantiate. Most probably, you want to write an utility *module* containing free functions. – Matteo Italia Nov 04 '14 at 06:41
  • Also, you should use `snake_case_names` for variables in Python, not `camelCase`... – pradyunsg Nov 04 '14 at 06:48

3 Answers3

2

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.

shx2
  • 61,779
  • 13
  • 130
  • 153
1

Class and instance attributes do not participate in the variable resolution process within a method. If you want to access them, you need to use ordinary attribute lookup syntax:

WebPageTestConfigUtils.configParser.read(self.configFilePath)

That said, you shouldn't be using a class at all for this. You seem to be used to a language where everything has to be in a class. Python doesn't work that way; you should just be using a module with ordinary functions in it.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

If you want to create static variable in your file, create before class definition. Generally in python static variable declare as UPPERCASE variable name.

For your example you can use

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

...
...
@staticmethod
def initializeConfig():
    CONFIGPARSER.read(CONFIGFILEPATH)
...
...
Nilesh
  • 20,521
  • 16
  • 92
  • 148