Home > front end >  Why is my python class being executed twice?
Why is my python class being executed twice?

Time:11-20

I am currently trying to write an script which takes an user input and then prints it out through a class which is located in another file. But when running my script I have to give the programm the input twice which is then being printed out thrice because of an weird reason. I also searched up some other similar questions on stackoverflow but none of them helped me fixing my problem.

This is the code in the first file:

#this is main.py
global test_input    
test_input = input('give me an input: ')
if 'i like cookies' in test_input:   
    from test import *
    test_class.test()

This is the code in the second file:

#this is test.py
class test_class():
    def test():
        from main import test_input
        print(test_input)

What the output looks like after running the script:

give me an input: i like cookies
give me an input: i like cookies #this second input is created because the function is being executed twice. In this example I would've typed in i like cookies twice
i like cookies
i like cookies 
i like cookies 

What the ouput should look like:

give me an input: i like cookies
i like cookies

I would be very very glad if someone could help me out with solving this problem and explaining to me what I've made wrong:)

Thank's for every suggestion and help in advance:)

CodePudding user response:

It is punishing you for bad programming practices. ;) The issue is that, when you run a program, that module is not considered to be imported. So, when you get into test_class.test(), your from main statement actually causes your main program to be loaded AGAIN. It will do the input call again, and will call test_class.test() again. This time, main has already been imported, so it doesn't need to do it again, and thing go normally.

It is horrible practice for a submodule to try to import something from a main module. If your module function needs a value, then pass it as a parameter.

  • Related