0

I am trying to writing a program to read a configuration file but while testing it am having this error:

self.connection_attempts = self.config_file.get('CONNECTION_ATTEMPTS', 'TIME')
AttributeError: 'list' object has no attribute 'get'

I ma pretty sure it is something I don't get, but it is few hours I am trying to understand where the problem is. My __init__ method looks like this:

import simpleconfigparser

class ReportGenerator:
    def __init__(self):
        self.config_parser = simpleconfigparser.configparser()
        self.config_file = config_parser.read('config.ini')
        self.connection_attempts = config_file.get('CONNECTION_ATTEMPTS', 'TIME')
        self.connection_timeout = config_file.get('CONNECTION_TIMEOUT', 'TIMEOUT')
        self.report_destination_path = config_file.get('REPORT', 'REPORT_PATH')

This code uses the SimpleConfigParser package.

sanna
  • 1,398
  • 5
  • 16
  • 24
  • 1
    `config_file` is a `list` object, hence your error – TayTay May 24 '18 at 12:19
  • Please refer to this post : https://stackoverflow.com/questions/5125619/why-doesnt-list-have-safe-get-method-like-dictionary – rak007 May 24 '18 at 12:19
  • I noticed, but in another program I wrote i used axactly the same code, only outside the __init__ method, and it works – sanna May 24 '18 at 12:20
  • `config_parser.read(...)` creates a list. Lists in python cannot be inquired by `.get`. Maybe you can convert it into a `dictionary` – offeltoffel May 24 '18 at 12:20
  • If `config_file` is a dictionary object this works with `get()`. The `config_file` might be a `list` object –  May 24 '18 at 12:21
  • @sanna: if you look carefully at the code where it works, you will notice that it is not the exact same code. in programming you have to be careful about little details, like the difference between `config_parser` and `config_file`. –  May 24 '18 at 12:30
  • Print the attribute, see how it looks like. It's a list. Depend on the contained objects you maybe can convert it into a dict. – Chen A. May 24 '18 at 12:30

1 Answers1

2

You want config_parser.get() not config_file.get(). config_parser.read() simply returns the list of config files successfully read after populating the config object. (Usually it is called config or cfg, not config_parser).

This list (config_file) serves no purpose in your code and you might as well not capture it at all.

from simpleconfigparser import simpleconfigparser

TIME = 5
TIMEOUT = 10
REPORT_PATH = '/tmp/'

class ReportGenerator:
    def __init__(self):
        self.config = simpleconfigparser()
        config.read('config.ini')

        self.connection_attempts = config.get('CONNECTION_ATTEMPTS', TIME)
        self.connection_timeout = config.get('CONNECTION_TIMEOUT', TIMEOUT)
        self.report_destination_path = config.get('REPORT', REPORT_PATH)

My guess would also be, that you use the default value in .get() the wrong way, but i cannot be certain with the information you have given.