Search code examples
pythonvariablesconfigparser

How do I procedurally assign more variables while the program is running?


I'm making a program that reads in data from a .ini file using configparser.py, so that I can create a Person object based on the information in the file.

My .ini's look like this:

[Pers1]
name = Alice

[Pers2]
name = Bob

...

[Pers25]
name = Xavier

I also have a class Person which takes the argument name, such that ExamplePerson = Person("Jim") creates a new Person object with the attribute ExamplePerson.name being "Jim".

So far, I've figured out how to read the .ini file, but I can't figure out how to write a function that take the file and manufacture objects from it.

I can manually create variables: Person1 = Person(name_from_ini_file), but I don't know how to write something like:

def make_objects_from_file(file_name):
    # read file_name, etc
    # get name from .ini file, store it as new_name
    # for item in file:
    PersX = Person(new_name)
    # PersX is Pers1 for the first object, then Pers2, and so on

So that I can call make_objects_from_file(persons.ini) and end up with Pers1 = Person("Alice"), Pers2 = Person("Bob"), ...Pers25 = Person("Xavier), or however many people are in the .ini file.

However, I don't how to create the initial Pers1 ... Per25 variables. I've looked into object factories, but either I'm misreading how they work or they aren't able to dynamically make more variables. I can't just type in Pers1 = ... , Pers2 = ... , Pers3 = ...; I need a way to make Pers1 ... in code. Not strings "Pers1", but actual variables.

This might help clarify:

NEW_OBJECT               =     Person(name)
    ^                            ^
I have no idea how to        I know exactly how to make this
make this

Solution

  • The idiomatic way to store a collection of named objects in Python is to use a dictionary, for you this might look something like

    names_list = ["alice","bob"] #from your file
    people = {"Pers"+str(i):Person(name) for i,name in enumerate(names_list)}