Search code examples
pythonfunctionpygamereturn

Is there any way to import a variable from a function in another file without using return in Python?


I have this pygame code which is divided into multiple files and in one of the files I want to import a variable from a function which is in another file.

# gamescreen.py
highscore = 0
def game_screen(screen):
    ...

    hits = pygame.sprite.spritecollide(player, world_sprites, True, pygame.sprite.collide_mask)
    if len(hits) > 0:
        if score > highscore:
            global highscore
            highscore = score
            state = PLAYAGAIN
    ...

    return state
# playagain.py
def play_again(screen):
    ...

    highscore_texto = font.render('highscore: {0}'.format(highscore), True, (BLACK))
    background.blit(highscore_texto, (30, 25))
    ...

Is there any way I can acess that highscore variable in the file playagain.py without having to return it in the game_screen function?

When I tried to return it in the game_screen function like this:

return state, highscore

And access it in the playagain.py file like this:

game_screen(screen)[1]

It just ran the game_screen function two times, which is not what I want because it messes up my game.


Solution

  • import gamestream
    print(gamestream.highscore)
    

    The variable is set in the module namespace (confusingly named "global" when its really "module global"). Import the module and you've got its namespace.

    This doesn't work

    from gamestream import highscore
    

    In that case you rebound the current thing in highscore to your module's namespace and it won't see changes to the original. It is the same as if you had done

    import gamestream
    highscore = gamestream.highscore
    

    A new variable called "highscore" is created in the local module and the current value in gamestream.highscore is bound to it. If gamestream.highscore is reassigned, that wouldn't affect this separate variable.