1

I am new to python, so please forgive me.

I have a module: beep.py, which contains a variable: p (contains a string) and function: ps. I need to access both of these from a module: boop, and use them there.

My problem is, if I try writing import beep in boop, then beep runs all of it's code. Is there some way to get around this?

1
  • How is beep laid out? Do you have a main() function, and/or use if __name__ == "__main__":? Commented May 15, 2014 at 21:52

2 Answers 2

2

Python executes all top level instructions when a module is imported. Well behaved modules that are intended to be importable should limit what they do with top level code. - they may run code at import, but it should not have side effects. It is common to use the if __name__ == '__main__' idiom to have a python module that can run as a script and as a imported module (see example).

If import beep causes problems, then either it was not designed to be imported or is is poorly written and needs to be fixed.

print 'i always run'

def fctn():
    print 'i run when called'

if __name__ == '__main__':
    print 'i run if called as a script but not if imported as a module'
Sign up to request clarification or add additional context in comments.

Comments

0

Python always evaluates the file that you import, so if you have some code outside a function or class, it will be executed. As tdelaney says you can protect the imported file using

if __name__ == '__main__':

I've create the full example here: https://gist.github.com/carlosvin/d9a1eb978fac226dbbe9

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.