0

I have a mymodyle.py module that contains a function called main:

def main(event):
    parser = Parse(event)
    parsed_event = parser.parse()
    return parsed_event

if __name__ == '__main__':
    event = "ABCD"
    main(event)

This function will be called from another module:

import mymodule

And the main function will be called via mymodule.main(event) - it will pass the event as an argument to main function of mymodule module.

If I run it from another module, do I need to add the dunder at the end because it won't be called anyway :

if __name__ == '__main__':
        event = "ABCD"
        main(event)

Another question: Do I need to add the else given that it will be called from another module?

if __name__ == '__main__':
            event = "ABCD"
            main(event)
else:
    //DO SOMETHING
1
  • 1
    If you don't want the module to be callable by itself, then you don't need the if __name__ part. That's the point of that construct: if the module is executed directly, do something. Otherwise… don't. Therefore you also don't need an else, if you don't need it. Commented Sep 7, 2021 at 13:47

1 Answer 1

1

If I run it from another module, do I need to add the dunder at the end because it won't be called anyway?

If you want your module to be both a "library" (import mymodule) and to also run your module with e.g. python -m mymodule or python mymodule.py, then yes.

Another question: Do I need to add the else given that it will be called from another module?

No, unless you want to do something only if your module is imported from another module. That's very rare.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.