0

This is not my code but I have a similar problem:

https://gist.github.com/songrotek/0c64d10cab5298c63cd0fc004a94ba1f

There are many parameters I want to edit and change in one central place (in the most semantic way possible) and then use to construct classes, run the main program etc.. Because I don't want to put everything in one file (it's too big, I need modules and different namespaces) and declare global variables. Having to edit the code for setting some parameters doesn't seem to be a good solution.

class Example:
    def __init__(self, *initial_data, **kwargs):
        for dictionary in initial_data:
            for key in dictionary:
                setattr(self, key, dictionary[key])
        for key in kwargs:
            setattr(self, key, kwargs[key])

Using constructors like this for being able to use dictionaries for init doesn't seem to be transparent enough.

What are possible solutions for this problem? It's still code mostly used by me and rather small, so it should be a good compromise between lightweight/appropriate for the size and still easy to use and comfortable.

I_like_foxes
  • 719
  • 1
  • 5
  • 10
  • You can pass a dictionary into `**kwargs`. For example, if your dictionary was called `d` you could pass `**d`. Is that what you mean? – cdarke Nov 03 '16 at 10:00
  • Not sure whether I understand your concern correctly, but does it go into the direction of what's been discussed here: [http://stackoverflow.com/questions/6198372/most-pythonic-way-to-provide-global-configuration-variables-in-config-py] – Dr. V Nov 03 '16 at 10:04

1 Answers1

0

A common way to handle this is a configuration file that is being read by ConfigParser.

Here is an example:

# configuration.ini
[Example1]

constant1: 1
constant2: 2

[Example2]

c1: 'one'
c2: 'two'

# test.py
from ConfigParser import ConfigParser

conf = ConfigParser()
conf.read('configuration.ini')

def configure_instance(instance):
    for i in conf.items(type(instance).__name__):
        setattr(instance, i[0], i[1])

class Example1(object):
    def __init__(self):
        configure_instance(self)

class Example2(object):
    def __init__(self):
        configure_instance(self)


e1 = Example1()
e2 = Example2()
print vars(e1)
print vars(e2)

# {'constant1': '1', 'constant2': '2'}
# {'c2': "'two'", 'c1': "'one'"}
hvwaldow
  • 1,096
  • 1
  • 9
  • 13
  • The drawback is that with the ini - file approach, all variables are strings. You could switch this to YAML (http://pyyaml.org/wiki/PyYAML) which autodetects the variable types. – hvwaldow Nov 03 '16 at 12:47