2

Im trying to run my code o vscode anda I have the following error while importing some constants from another file: "ImportError: attempted relative import with no known parent package".

import pygame
from .constants import BLACK, ROWS, RED, SQUARE_SIZE


class Board():

    def __init__(self):
        self.board = []
        self.selected_piece = None
        self.red_left = self.white_left = 12
        self.red_kings = self.white_kings = 0

    def draw_squares(self, win):

        #Win es window

        win.fill(BLACK)
        for row in range (ROWS):
            for col in range(row % 2, ROWS, 2):
                pygame.draw.rect(win, RED (row*SQUARE_SIZE, col*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))

The file constants just contains some constants with height and width of the window

constants.py

import pygame

WIDTH, HEIGHT = 800, 800
ROWS, COLS = 8,80
SQUARE_SIZE = WIDTH//COLS

RED = (255,0,0)
WHITE = (255,255,255)
BLACK = (0,0,0)
BLUE = (0,0,255)
MateoG98
  • 183
  • 11
  • @Rabbid76 thank you very much, i was not aware of this. – MateoG98 Dec 15 '20 at 18:51
  • Does this answer your question? [Attempted relative import with no known parent package](https://stackoverflow.com/questions/55084977/attempted-relative-import-with-no-known-parent-package) – sedavidw Dec 15 '20 at 18:55

1 Answers1

1

This article explains pretty well what is going on. Basically Python struggles with doing relative imports when __name__ == '__main__'. I think the following alternatives would all work:

  1. You can run your script using cd C:\Users\Mateo\Desktop\Python\Checkers && python -m checkers.board

  2. Instead of running board.py directly, run main.py, and have it import checkers.board.

  3. Don't use relative imports, and instead just do from constants import BLACK, ROWS, RED, SQUARE_SIZE.

hostingutilities.com
  • 8,894
  • 3
  • 41
  • 51