I am a Java programmer dabbling in Python for the first time. Mostly, the transition has been pretty smooth, but this week something stumped me. Please forgive me if the answer to this is completely obvious - I've read van Rossum's tutorial and can't figure it out.
I am working on a Python project composed of one main module and several smaller helper modules. Each module is currently in its own file, which (I believe) is the convention Python uses. The main module is called MainProgram.py and one of the helper modules is called Helper.py. MainProgram.py has to import a method called somefunc() from Helper.py.
Now, one of the conventions I use when designing OO systems in Java is this: all of my helper classes have diagnostic code in their main methods, so that when you invoke the class's main from the command line, you get to see whether the methods of that class work the way they are supposed to. Unfortunately, Python modules have no main method to speak of, so I did what I thought was the next best thing. In my Helper module:

# Helper.py

def somefunc(a, b, c):
     # code for this function

# Code that tests somefunc
somefunc('A', 'B', 'C')

The idea is that somefunc() executes with arbitrary arguments of 'A', 'B', and 'C' when Helper.py is invoked on its own. Then, in the MainProgram module:

# MainProgram.py

from Helper import somefunc
somefunc('Actual', 'data', 'here')
# Other code which does other stuff

Right? Unfortunately, the import statement also triggers that diagnostic invocation of somefunc() at the bottom of Helper.py - this is neither trivial nor good in the context of my actual project. It's also very confusing, since you'd think that importing a method from a module wouldn't call for any execution at all.

Can anyone tell me if there's a way to do what I'm describing in Python? Again, I'm sorry if this is a total n00b question - that's what I am at the moment.

11 Years
Discussion Span
Last Post by G-Do

In your Python folder there is a folder \lib\test\ that should give you an idea how the Pythonians do their testing of modules. It looks like you might need to write a simple test program. Also IDEs like IDLE have a check module option.

Hope someone else knows more about that subject. I started using Python more seriously about 5 months ago and have great fun with it, but have not touched every corner of its many capabilities.



Thank you very much, vegaseat. That:

if __name__ == '__main__':
     # Test code here

...was just what I needed. And the article was very informative - I knew about doctest and unittest, but not enough. Thanks!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.