Jump to content

[Python] Modifying global variable from within a function


Recommended Posts

sure it is. But you are using two different vars here 🙂

 

If you use the keyword global, the following variable(s) are taken from the global symbol context, which is valid for the whole script.

If you do not use that keyword and create a variable by using an identifier and assign a value to it, the variable is known only to the current function.

 

So, in your main() you create a local variable var. Local for main, mind you.

Then in your call of Change_var, you declare your usage of the symbol var as global, and create another variable var by assigning, this time in the global scope.

Then you print the first var, which is still local to main and has never changed its value.

 

If you mean to address the same global symbol, you need to declare global var in main, too!

 

def main():
    global var
    var = 0
    
    def changevar():
        global var
        var = 1
        
    changevar()
    print var

 

The problem with Python is that you never explicitly create/declare a variable; Python does that for you the moment you use an identifier as lvalue. That however means that you sometimes cannot address variables from another function's context in the case of nested functions - you can use them as rvalue (reading) but once you assign a value, Python thinks you want a new variable. global, on the other hand, uses only the script-global scope. So, nesting is a bit problematic in general.

 

----------
Learn more about Python on C4D:
https://www.patreon.com/cairyn

Link to post

P.S. The "trinket" code works that way because there is no main() function, so the first occurrence of var is already global instead of bound to a function!

You can get the same effect by dropping the main() function in C4D and make the code start on the outermost, global level (without the if __name__=='__main__': stuff). Just if you doubt that C4D's Python is correct 🙂

Link to post

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...