user2921888
user2921888

Reputation: 25

Import same python module more than once

I am trying to find a way of importing the same module more than once due to a certain key press....

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_1:
        import forest_level
    if event.key == pygame.K_2:
        import sea_level
    if event.key == pygame.K_3:
        import desert_level
    if event.key == pygame.K_4:
        import underwater_level
    if event.key == pygame.K_5:
        import space_level

say if I were in the forest level and went to the sea level, how would I get back to forest level?

GAME CODE

Upvotes: 1

Views: 2429

Answers (1)

SingleNegationElimination
SingleNegationElimination

Reputation: 156258

You can't.

I'm going to have to guess the structure of your code, since you havent quite provided a Short, Self Contained, Correct (Compilable), Example.

You probably have several modules that look like:

# foo_level.py
print "foo"

along with a main module:

# main.py
while True:
    key = raw_input()
    if key == "foo":
        import foo_level
    # and so on.

the import statement is designed for bringing code into scope, not for actually executing any code.

Put all of the code you want to run multiple times in a function:

# foo_level.py
def do_stuff():
    print "foo"

and instead, import all modules once, at the beginning and call the new functions inside the loop:

# main.py
import foo_level
while True:
    key = raw_input()
    if key == "foo":
        foo_level.do_stuff()
    # and so on.

Upvotes: 3

Related Questions