Python Forum
module run on import? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: module run on import? (/thread-24738.html)



module run on import? - mcmxl22 - Mar-02-2020

I have this game I am working on. I am trying to use a config.py file for global variables like this.
from os import system

clear_screen = system("cls")
quit_game = exit(0)
output:
Output:
PS C:\Users\mcmxl>
I have also tried this. and get an attribute error.
from os import system

if __name__ == "__main__":
    clear_screen = system("cls")
    quit_game = exit(0)
Error:
Guess a letter. Traceback (most recent call last): File "c:/Users/mcmxl/mystuff/hangman/hangman.py", line 46, in main guess_letter = input("Guess a letter. ") KeyboardInterrupt During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:/Users/mcmxl/mystuff/hangman/hangman.py", line 112, in <module> main() File "c:/Users/mcmxl/mystuff/hangman/hangman.py", line 49, in main config.clear_screen AttributeError: module 'config' has no attribute 'clear_screen'
I don't know what else to do.


RE: module run on import? - Gribouillis - Mar-02-2020

Define functions in config.py
from os import system
import sys

def clear_screen():
    system("cls")

def quit_game():
    sys.exit(0)
Then in your program, call the functions (notice the parentheses)
...
config.clear_screen()



RE: module run on import? - buran - Mar-02-2020

@mcmxl22, and what is the purpose to have these two in a config file? First of all its not configuration file per se (i.e. there is no configuration in what you do). Second, it just obscure what is done, why not simply use system('cls') instead of whatever implementation you go for? Third - cls is Windows. For example on Linux the command is clear. Using cls makes your game platform-specific.


RE: module run on import? - mcmxl22 - Mar-02-2020

@buran My reasoning for the config file was to try to simplify the game file. I thought it was getting too long and complicated.

Thanks for pointing out the cross-platform issue. I'm thinking I'll use a try/except to fix it and put it in its own function.

@Gribouillis thanks for the explanation of putting it in functions.