-1

Warning: This question isn't a duplicate of the old "How do I create a bunch of variables in a loop?" because it uses a special class with arguments. If code actively disrespectful to PEP8 makes your eyes bleed, go no further, traveler!

Ok, I'm writing some code for a graph of objects in a detailed network and I want the code itself to look a particular way. For the purposes of this question, this means that I do not want to write the code such that I am referencing a dictionary with keys generated in a loop that reference instances of my special class. I want to write the code in a minimal way that I am aware is non-Pythonic, yet acceptable to my awful psychological makeup.

So: how should the code for the function instantiate shown below be written? The idea is that this function instantiates a variable with the name specified using the special class Relay that has some arguments.

import uuid

def generate_Python_variable_names(
    number = 10
    ):

    names = []
    while len(names) < number:
        name = str(uuid.uuid4()).replace("-", "")
        if name[0].isalpha():
            names.append(name)

    return names

number_relays = 100

for name in generate_Python_variable_names(number = number_relays):
    instantiate(name, Relay(configuration = 1)
Community
  • 1
  • 1
BlandCorporation
  • 1,324
  • 1
  • 15
  • 33

1 Answers1

1

I make the assumption that you are at module level. And what you want is to create new variables in the current module.

To do this, you can use the globals() function to have access to the module's variables.

for name in generate_Python_variable_names(number=number_relays):
    obj = globals()
    obj[name] = Relay(configuration=1)

If you print the variables, you will get something like this:

{'Relay': <class '__main__.Relay'>,
 '__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__file__': 'path/to/your/module.py',
 '__name__': '__main__',
 '__package__': None,
 'df55cd5884924e88a4a13371b248d755': <__main__.Relay object at 0x105f66fd0>,
 'e11d3a1e3afb4ada801e08d57219e9be': <__main__.Relay object at 0x105f66550>,
 ...
 'ef93466af4a34e7b8ec28568cca664f5': <__main__.Relay object at 0x105f66ed0>,
 'generate_Python_variable_names': <function generate_Python_variable_names at 0x105f670c8>,
 'name': 'ef93466af4a34e7b8ec28568cca664f5',
 'number_relays': 100,
 'obj': <Recursion on dict with id=4394090856>,
 'uuid': <module 'uuid' from 'path/to/uuid.pyc'>}

As you can see, you have one hundred of new variables in your module.

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103