Search code examples
pythonvariablespygameglobalgeometry-surface

Python and Pygame: Avoiding creating display surface twice


Heyo, this is a bit of an extension of the "Imports within imports" question asked earlier by me, so moderators feel free to merge the 2.

I have 2 files: A.py and B.py

#A.py
import pygame
import B
pygame.init()
tv = pygame.display.set_mode((256, 256))
tv.blit(<some surface here>)


#B.py
import pygame
pygame.init()
tv.blit()??? <--- I need to blit to tv, but how do I do it here?

I've tried making a blank file called Globe and assigning global values to it, but most of the time I've found it just makes my code look clunky and hard to write. As well.. I don't want to init pygame twice either. Is there any 'Pythonic' way to do it?


Solution

  • This question could really apply to any structured python application.

    An executable python script is going to have an entry-point. This is the script that you call to start the application. Within this script, it can import library modules to reuse extended functionality.

    Your application needs to have a single entry point. Lets assume it will be A.py.
    B.py would be a library module that you will import and use its functions. It should not have to expect a global tv variable to operate on. Instead, it should have, at the very least, functions that take arguments. Or even, a class that is instantiated with a surface to use. The benefit of this approach is that your B module is now reusable and not dependent on some executable main script providing a global surface always called tv

    B.py

    def blitSpecial(surf):
        surf.blit()
    

    A.py

    import B
    
    tv = pygame.display.set_mode((256, 256))
    B.blitSpecial(tv)
    

    This is a good habit to get into. If all your modules depend on global objects from a main script, they will be far less reusable.

    Specifically for your pygame situation, everything with the screen surface should be happening in A.py which is using all of the other modules for custom classes and utility functions.