Search code examples
pythondynamicparametersglobal-variables

Creating a global variable passed as parameter


I'm trying to create a function, that would take a parameter, then make a global variable out of it(more precisely an instance of a class).

class SomeClass():
    #some stuff defined inside

def create(crt, **kwargs):
    globals()[crt] = SomeClass()
    for key, value in kwargs.items():
        if crt.__dict__.__contains__(key):
            crt.__setattr__(key, value)
    return crt

Output that I'm interested in would be:

create(foo, class_attribute=10)

That would then allow me to:

foo.other_attribute = "whatever"

I can't pass a parameter without '' if it's not defined earlier, neither can I pass a string, because it's not a variable in itself, hence it can't be an instance of a class.

Would that be even possible?


Solution

  • This is a bad idea, but here's how to do it.

    You need to pass the name as a string. When you're setting the attributes, do it on a local variable that contains the new object.

    def create(crt, **kwargs):
        obj = SomeClass()
        for key, value in kwargs.items():
            if obj.__dict__.__contains__(key):
                obj.__setattr__(key, value)
        globals()[crt] = obj
        return obj
    
    create('foo', class_attribute=10)
    foo.other_attribute = 'whatever'