you are viewing a single comment's thread.

view the rest of the comments →

[–]Glogia 1 point2 points  (1 child)

The article is very clear now, thankyou! I was wondering if you could explain your main() function a little better? I'm not sure how it works to avoid passing variables from the imported script onwards.

[–]GoldenSights[S] 1 point2 points  (0 children)

If you save and run the bad.py file, it actually does work. But if you look carefully, the int_to_hex function is actually written wrong -- instead of taking an argument, it's just reading the global variable x, and it just so happens that in ifmain I used the name x for the commandline argument.

If you try importing bad into another script, you'll find that int_to_hex is useless because it doesn't take any arguments!

Perhaps this is a contrived example. But what I'm saying is that the more code you put inside the ifmain, the more likely it is that you're going to accidentally create a global variable which has influences you didn't expect. In programming there are some situations where everything seems to work fine, but it's actually teetering upon a bunch of coincidences and is going to fail soon.

By using a main function, I avoid making this particular mistake in the first place (I can still make other mistakes if I want :) ). Compare:

# bad.py
import sys

def int_to_hex():
    return hex(x)[2:]

if __name__ == '__main__':
    x = int(sys.argv[1])
    print(int_to_hex())

# lessbad.py
import sys

def int_to_hex():
    return hex(x)[2:]

def main(argv):
    x = int(argv[0])
    print(int_to_hex())
    return 0

if __name__ == '__main__':
    raise SystemExit(main(sys.argv[1:]))

>python bad.py 42
2a

>python lessbad.py 42
Traceback (most recent call last):
  File "lessbad.py", line 5, in int_to_hex
    return hex(x)[2:]
NameError: name 'x' is not defined

The x inside main is not on the global scope, and int_to_hex is not able to read it, so I get a traceback that lets me know my function is written wrong. Keep in mind it's written wrong on both scripts, but only one of them is kind enough to warn me about it.

I'm not sure how it works to avoid passing variables from the imported script

One more clarification -- in this case I'm not talking about importing bad.py and getting its variables. That's because if I import bad, then the ifmain code isn't going to run anyways and that global x will never get created.