3

I am trying to have a module that provides a framework of sorts to short declarative one-file scripts that I write. In the short scripts, I would like to define a number of variables and functions that are accessed or called back by the framework module.

I am stuck ... I have tried two approaches, and I am not crazy about either one. Is there a better way?

First approach:

Framework module:

import __main__
def test():
    print __main__.var
    print __main__.func()

Script:

import framework
var="variable"
def func():
    print "function"
framework.test()

I like this approach and it works, but eclipse gives me an 'Undefined variable from import: var' error on any imported variable or function from main. Obviously, this is not correct as it works, but it clutters up eclipse with many false errors.

Second Approach:

Framework module:

def test(glob):
    print glob['var']
    print glob['func']()

Script:

import framework
var="variable"
def func():
    print "function"
framework.test(globals())

This seems to work and does not give me errors, but I don't like the dictionary type notation used to call variables and functions ... especially for functions: func'funcName'.

Is there a better way to implement this that results in clean code? Can I pass in a module name (ie main) as an argument to a function? Can Eclipse errors on main for the first approach be turned off?

user4061565
  • 545
  • 1
  • 5
  • 16
  • How about `def test(var, func):` in the module, and `framework.test(var, func)` in the script? Or is your example a simplification and your real code has lots of dependencies and it would be burdensome to pass a variable for each one? – Kevin Apr 27 '15 at 16:47
  • 1
    Yap, this is an oversimplification ... there will be many variables and functions. – user4061565 Apr 27 '15 at 16:52
  • OT: glob is a bad variable name... – Joran Beasley Apr 27 '15 at 17:06
  • 1
    Using `__main__` seems a perfectly reasonable solution. For the Eclipse nonsense, see [how-do-i-fix-pydev-undefined-variable-from-import-errors](https://stackoverflow.com/questions/2112715/how-do-i-fix-pydev-undefined-variable-from-import-errors). – ekhumoro Apr 27 '15 at 18:23
  • @ekhumoro Thanks! command+1 works great to ignore the undefined variable error – user4061565 Apr 27 '15 at 18:58

1 Answers1

1

I went with the first approach and told Eclipse to ignore the Undefined Variable from Import error by pressing command+1 (for my Mac, for Windows it would be ctrl+1) on each line where this error occurred.

command+1 adds the following comment to the end of each line:

# @UndefinedVariable

Thanks to @ekhumoro for pointing this out in the comments.

user4061565
  • 545
  • 1
  • 5
  • 16