PixelWarrior
PixelWarrior

Reputation: 29

Get a single variable and a single function from a module without executing the module?

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?

Upvotes: 1

Views: 61

Answers (2)

tdelaney
tdelaney

Reputation: 77387

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'

Upvotes: 2

carlosvin
carlosvin

Reputation: 979

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

Upvotes: 0

Related Questions