h1h1
h1h1

Reputation: 780

Python - Function Name Importation

I'm importing a package for a game with functions such as moveUp(), moveDown(), moveLeft() and moveRight(). I am trying to create a function that will loop any of these commands for a designated number.

I am currently using the following code:

def moveUpLoop(loopNo):
    for i in range(0, loopNo):
        world.moveUp()

def moveDownLoop(loopNo):
    for i in range(0, loopNo):
        world.moveDown()

def moveLeftLoop(loopNo):
    for i in range(0, loopNo):
        world.moveLeft()

def moveRightLoop(loopNo):
    for i in range(0, loopNo):
        world.moveRight()

However I would like to use something like the following:

def functionLoop(funcName, loopNo):
    for i in range(0, loopNo):
        world.funcName()

functionLoop(moveRight, 5)

When I try to do this, I get this error:

NameError: global name 'moveRight' is not defined

Is there anyway around this? Thanks for any help

Upvotes: 0

Views: 87

Answers (2)

Max Noel
Max Noel

Reputation: 8910

getattr is the function you're looking for. However, that sort of pattern seems more suited to a dictionary:

direction_mapping = {
    "up": world.moveUp,
    "down": world.moveDown,
    "left": world.moveLeft,
    "right": world.moveRight
}

def move_loop(direction, loopno):
    direction_func = direction_mapping[direction]
    for i in range(loopno):
        direction_func()

move_loop("right", 5)

Of course, at that point I'd probably even change the whole design so that world has a move method that takes a direction argument.

Upvotes: 0

Paul Draper
Paul Draper

Reputation: 83235

def functionLoop(funcName, loopNo):
    for i in range(loopNo):
        getattr(world, funcName)()

functionLoop('moveRight')

or

def functionLoop(func, loopNo):
    for i in range(loopNo):
        func()

functionLoop(world.moveRight)

Upvotes: 3

Related Questions