Monday 15 August 2011

python - Confused about variable scope using matplotlib -- axis object -



python - Confused about variable scope using matplotlib -- axis object -

i have no thought why next code works. if comment out ax assignment in main, ceases work. how ax in scope of function? python version 2.7.2.

after little more research, i've found functions defined in same code module see variables in main block. had no thought python worked way! every variable in main block visible functions in same source file. not strike me desirable! seems violate functions about. suppose exception made main code blocks, not have guessed it.

how prevent functions defined in code module seeing variables in main block?

import pylab plt def f(): ax.plot([1],[2]) # how ever defined? homecoming if (__name__ == "__main__"): fig = plt.figure() plt.clf() ax = plt.subplot(111,polar=true) # if comment out, ax not defined error in function phone call plt.hold(true) f()

"this not strike me desirable! seems violate functions about."

you should avoid having global variables in code. note main block you're referring to, global namespace (of module/script). there if-statement, doesn't mean "main" block special function.

what can (which considered improve anyway):

import pylab plt def f(): ax.plot([1],[2]) # never defined homecoming def main(): fig = plt.figure() plt.clf() ax = plt.subplot(111,polar=true) # ax local main() function only. plt.hold(true) f() if __name__ == "__main__": # no parentheses if-statement; un-pythonic main()

now, cause error every time, because ax defined within main(), , not in global (module) namespace.

python matplotlib

No comments:

Post a Comment