1

I created a function in python which I invoke from another file. However, it is getting invoked twice.

The following function is in test.py -

def test_fun():
    print("test fun invoked")

I am invoking that function from __init__.py file as follows

from sample.test import test_fun

test_fun()

But test_fun is getting executed twice.

I am getting the output as-

test fun invoked

test fun invoked

Am I doing something wrong?

Haran Rajkumar
  • 2,155
  • 16
  • 24
Arun Kumar
  • 91
  • 1
  • 7
  • 2
    first thing you do wrong is you did not provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) as the question is stated now we cant answer what went wrong, maybe try to remove the function call and if the function is still called it is because of the import ... any answer would be a guess – Derte Trdelnik Mar 22 '19 at 08:02
  • Thanks, @DerteTrdelnik, But I have already check that if I remove the function call than the function don't execute. I also tried to change the import as I import only the file not, a particular function, but it's also not worked for me. – Arun Kumar Mar 22 '19 at 08:24
  • 1
    @Arun Please look at the post that Derte linked you too. Without providing that information as an [edit] to your question - there's nothing anyone can help you with. – Jon Clements Mar 22 '19 at 08:40
  • @DerteTrdelnik, Please review the edited question, Not sure but I think it is happening because I am invoking the function from the __init__ file. Am I right? – Arun Kumar Mar 22 '19 at 09:12
  • Can you tell which file you are executing? Are you directly running the `init` file or are you executing a different file? – Haran Rajkumar Mar 22 '19 at 09:23
  • @HaranRajkumar yes I am executing __init__ file directly. – Arun Kumar Mar 22 '19 at 15:28
  • @ArunKumar I have tried to replicate your output. I have the same two files. `__init__.py` is in the root folder. `test.py` is in a folder `sample` in the root. I ran the `__init__.py` file and the function is getting invoked only once. Can you provide your file structure? – Haran Rajkumar Mar 25 '19 at 03:54

1 Answers1

2

__init__.py gets executed whenever you load a package since there is a function call in it it will get executed even if you import something from the package see What is __init__.py for?

you should wrap executions meant for when the module itself is executed in a check whether it is actually called as a main otherwise the modules are not safe to be imported...

if __name__ == '__main__':
    test_fun()
Derte Trdelnik
  • 2,656
  • 1
  • 22
  • 26