Search code examples
pythonfunctionstub

How do I stub functions in python?


It's my first few lessons in programming and i've encountered a question that i don't really understand how to proceed.

def defeat_balrog(protagonist):    
    def spawn_balrog():
        """Spawns and returns a stubborn balrog"""
        pass
    def balrog_attack(balrog, person):
        """Returns an attack move from the balrog's repertoire"""
        pass
    cave_balrog = spawn_balrog()
    is_balrog_defeated = False
   yell(protagonist, 'You cannot pass!')
    while not is_balrog_defeated:
        current_attack = balrog_attack(cave_balrog, protagonist)
        if current_attack != None:
            take_defensive_action(protagonist, current_attack)
        yell(protagonist, 'YOU SHALL NOT PASS!')
        take_offensive_action(protagonist, cave_balrog)
        is_balrog_defeated = True
    return True

def take_defensive_action(attacked_entity, attack_move):
    """
    attacked_entity anticipates attack_move and defends himself.
    """
    pass
#my stubs here#
defeat_balrog('gandalf')

I'm supposed to identify the remaining functions that have been wishfully used, but for which stubs have not been created, and fill in from the last line #my stubs here#. not sure how to get started or proceed on.


Solution

  • A stub is a function that exists but for which no meaningful business logic has been defined. For example:

    def take_defensive_action(attacked_entity, attack_move):
        pass
    

    Notice the pass statement here? It means that you've defined a valid function, but it does nothing.


    Pasting your code into PyCharm, I see the following functions highlighted in "yellow" (that means those function names have an Unresolved reference):

    • yell(protagonist, 'YOU SHALL NOT PASS!')

    • take_offensive_action(protagonist, cave_balrog)

    Clear on the meaning of what a stub is, you should be able to define these functions accordingly as they haven't been defined yet. Here's an example for yell:

    def yell(protagonist, message):
        pass
    

    I leave the second to you.