Search code examples
pythonlistfunctionmaya

Using a list in multiple Functions


Is it possible to use a list created in one function in a separate function?

I've created a list of discs in this function:

def create_discs():

    disc_list=['disc0', 'disc1', 'disc2']

I would then like to use this list in a different function

def move_discs

    cmds.move(disc_list[1], 0, 0, 5)

I get this error when trying to do so:

NameError: file <maya console> line 48: global name 'disc_list' is not defined #

I'm using Autodesk Maya


Solution

  • If you don't want to use Classes to maintain state, then you may want to have a global variable or you can return the list from create_list().

    Using global variable:

    disc_list = []
    
    def create_list():
        global disc_list
    
        disc_list = ['disc0', 'disc1', 'disc2']
    
    def move_discs
        cmds.move(disc_list[1], 0, 0, 5)
    

    Note that using global variables is not encouraged.

    Returning list from create_list():

    def create_list():
        return ['disc0', 'disc1', 'disc2']
    
    def move_discs():
        disc_list = create_list()
        cmds.move(disc_list[1], 0, 0, 5)
    

    But I don't think this will of much help to you as you probably need to keep the state of your list throughout the program.