Search code examples
pythonimportpygame

How to import libraries from a specific folder in Python?


I installed pygame in my project folder (the folder where the script gets executed) because I don't want the user to download the requirements or run a setup file. First I tried installing pygame in the project folder and importing it with import pygame and everything went as expected. To install it in the lib folder I used the following command:

pip install --target=...\project-folder pygame

But when I tried installing pygame in a 'lib' folder, and importing it with

from lib import pygame

or

import lib.pygame as pygame

it doesn't work and it gives the following error:

from pygame.base import *  # pylint: disable=wildcard-import; lgtm[py/polluting-import]
ModuleNotFoundError: No module named 'pygame'

I noticed a lot of simple games have a 'lib' folder but I don't understand how they do it.


Solution

  • You may add project's folder to sys.path before you import module.

    import sys
    
    sys.path.append("\full\path\to\project-folder")
    
    import pygame
    

    To make sure you can insert it as first element on list.
    It will always get module from your folder - even if you will have pygame installed also in global folder.

    sys.path.insert(0, "\full\path\to\project-folder")
    

    To make it more universal you may try to get project folder using __file__ - and it should work even if you move all code to other folder.

    import os
    import sys
    
    BASE = os.path.dirname(os.path.abspath(__file__))
    
    sys.path.insert(0, BASE)
    
    # if `pygame` is in subfolder `lib`
    sys.path.insert(0, os.path.join(BASE, 'lib'))
    

    If you load some images/sounds/etc. then you can also use it

    enemy_img = pygame.image.load( os.path(BASE, 'images', 'enemy.png') )