0

I want to know which way the best is for importing modules.

I'm currently using multiple files for my Pygame-Game. There are the main files and there is also a file where I import everything from.

It's like this:

settings.py:

import pygame,random,os,...

a main game file:

from settings import pygame

Everything works fine but should I do it instead like this?

a main game file(rewriten):

import pygame
Twistios_Player
  • 120
  • 3
  • 11

2 Answers2

0

As the link bellow said, import necessary modules in another module, is a good shape looking code. For large projects it is a necessary work, because every thing going to be crazy.
Python import modules in another file

Saeed Bibak
  • 46
  • 10
0

The first way to import modules implies that there's a reason you import pygame from settings and not directly.

You might have modified some variables, functions or objects from pygame in settings.py, so that the stuff imported from settings.pygame has different behavior than that imported from pygame directly.

Just for the sake of an example (of how not to do it I'd say):
Say your pygame.py has a function like:

enemy_action( In_1, ... , In_n, DIFFICULTY )

In your settings.py you now probably have the difficulty setting stored, so you could redefine the function with DIFFICULTY already set by creating a decorator for the function:

pygame.DIFFICULTY = DIFFICULTY

def pygame.difficulty_setter(f):
    def inner(*x, DIFFICULTY = pygame.DIFFICULTY):
        return f(*x,DIFFICULTY = pygame.DIFFICULTY)
    return inner

If you now set

enemy_action = pygame.difficulty_setter(enemy_action)

The function enemy_action wouldn't need to be passed the DIFFICULTY parameter anymore.

Sanitiy
  • 308
  • 3
  • 8
  • So there is no performance boost if I'm importing all modules every time(even if i need say pygame.mixer in the first file but not pygame.image and pygame.image in the second file but not pygame.mixer from my settings.py; both files are parts of the game)? – Twistios_Player Aug 04 '17 at 10:19
  • The performance part is mostly a theoretic value in this case. To actually affect your program you'd need an absurd amount of functions. I just tested it out: one script with 1 function, the other with 1000 functions. Having 999 extra functions added... 9 ns per function call. – Sanitiy Aug 04 '17 at 15:38