Is there an equivalent in Python of Fortran's "implicit none"? -


in fortran there statement implicit none throws compilation error when local variable not declared used. understand python dynamically typed language , scope of variable may determined @ runtime.

but avoid unintended errors happen when forget initialize local variable use in main code. example, variable x in following code global though did not intend that:

def test():     y=x+2  # intended x local variable forgot            # x not initialized      print y   x=3 test()  

so question that: there way ensure variables used in test() local , there no side effects. using python 2.7.x. in case there local variable, error printed.

so question that: there way ensure variables used in test() local , there no side effects.

there technique validate globals aren't accessed.

here's decorator scans function's opcodes load_global.

import dis, sys, re, stringio  def check_external(func):     'validate function not have global lookups'     saved_stdout = sys.stdout     sys.stdout = f = stringio.stringio()     try:         dis.dis(func)         result = f.getvalue()     finally:         sys.stdout = saved_stdout     externals = re.findall('^.*load_global.*$', result, re.multiline)     if externals:         raise runtimeerror('found globals: %r', externals)     return func  @check_external def test():     y=x+2  # intended x local variable forgot            # x not initialized     print y 

to make practical, want stop list of acceptable global references (i.e. modules). technique can extended cover other opcodes such store_global , delete_global.

all said, don't see straight-forward way detect side-effects.


Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -