Search code examples
pythonpython-2.7maya

Running file on global variables


So this is a piece of the code:

global episode = "Episode404"
import testing
reload (testing)
#or
python testing.py

testing.py:

def doIt():
    print episode
doIt()

And this throws me

# Error: invalid syntax # 

I'm guessing this is because I'm trying to pass a global variable and run? How can I fix this?


Solution

  • The line below is wrong:

    global episode = "Episode404"
    

    But you are also misunderstanding the concept of global command. You need to use it to change the value of some variable defined outside of the scope that you are currently working.

    What Andy answered works, but it is not necessary, as you can do this with the same result:

    episode = "Episode404"
    
    def doIt():
        print(episode)
    
    doIt()
    

    global here would be only necessary if you want to change the value of episode inside doIt() with this change being propagated outside of the scope of doIt() like this:

    episode = "Episode404"
    
    def doIt():
        global episode
        print(episode)
        episode = "New Episode"
    
    doIt()
    print(episode)
    

    and the output will be:

    "Episode404"
    "New Episode"
    

    If you really need to use different modules, why don't you just pass the episode as an argument for doIt()?

    Put this on your testing.py

    def doIt(episode):
        print(episode)
    

    And then change your main code to:

    from testing import doIt
    
    episode = "Episode404"
    doIt(episode)
    

    I think this approach is better than using global variables and trying to share them between modules. Probably you can do that only using hacks or things that you probably don't need.