L. de Boer L. de Boer - 13 days ago 5
Python Question

mixing up pygame.time() and time.time()

For a minesweeper game I am using time.time(), I have imported both time and pygame. Here is my error report;

line 5, in save_score
end = time.time()
AttributeError: module 'pygame.time' has no attribute 'time'

Here you have the proof that I did import both time and pygame:

import sys, math, time
def save_score(name, size, mine):
end = time.time()
from pygame import *

If anyone can explain how to avoid/ fix this error, it'd be much appreciated.


You're encountering a namespace collision, due to your line:

from pygame import *

This is polluting your global namespace with everything you can import from pygame. It makes lazy life easy - you don't have to refer to the specific namespace to use pygame's functions. But it has some bad consequences, too.

In this case, you had imported "time" as a module in the global namespace. When you import as you did from pygame, it had a submodule called time. pygame.time replace your regular time module.

The way to fix this is to use module/namespaces properly.

One way to do that, is instead of using from pygame import *, instead use:

import pygame

But then you have to put pygame in front of every reference to a pygame function or module. This is generally good, that way you and anyone else who reads your code knows exactly what function you're calling.

You can abbreviate it a little bit, using import ... as:

import pygame as pg

Then instead of doing things like pygame.time, you would do pg.time.

If there are some things you want to specifically put into the global namespace, you can do things like:

from pygame import foo


from pygame import time as pygt

But if you do from pygame import time or from pygame import *, pygame's time will overwrite the other time module.