Python global dynamic variable declaration

I am new to python / programming, and maybe my question doesn't make any sense.

My problem is that I cannot force a variable to be global if it is dynamic, I mean that I can do this:

def creatingShotInstance():

    import movieClass

    BrokenCristals = movieClass.shot()
    global BrokenCristals #here I declare BrokenCristals like a global variable and it works, I have access to this variable (that is a  shot class instance) from any part of my script.
    BrokenCristals.set_name('BrokenCristals')
    BrokenCristals.set_description('Both characters goes through a big glass\nand break it')
    BrokenCristals.set_length(500)
    Fight._shots.append(BrokenCristals)

def accesingShotInstance():
    import movieClass

    return BrokenCristals.get_name()#it returns me 'BrokenCristals'

but if instead I declare a string variable as follows:

def creatingShotInstance():

    import movieClass

    a = 'BrokenCristals'

    vars()[a] = movieClass.shot()
    global a #this line is the only line that is not working now, I do not have acces to BrokenCristals class instance from other method, but I do have in the same method.
    eval(a+".set_name('"+a+"')")
    eval(a+".set_description('Both characters goes through a big glass\nand break it')")
    eval(a+".set_length(500)")
    Fight._shots.append(vars()[a])

def accesingShotInstance():
    import movieClass

    return BrokenCristals.get_name()#it returns me 'BrokenCristals is not defined'

I tried this:

global vars()[a]

and this:

global eval(a)

but it gives me an error. What should I do?

+3
source share
3 answers

Instead of a dynamic global variable, use dict:

movies = {}

a = 'BrokenCristals'

movies[a] = movieClass.shot()
movies[a].set_name(a)
# etc
+7
source

For completeness, here is the answer to your original question. But this is almost certainly not what you wanted to do - there are very few cases where you need to change the area dict.

globals()[a] = 'whatever'
+9

The global keyword indicates that the variable you use in the same scope actually belongs to the outer scope. Since you do not have nested areas in your example, the global does not know what you are trying to do. See Using global variables in a function other than the one that created them.

+1
source

Source: https://habr.com/ru/post/1776880/


All Articles