Menu

Problems with __main__

2014-07-15
2014-07-15
  • Doug Jenkins

    Doug Jenkins - 2014-07-15

    I have a couple of functions that use getattr() to return a function object, given the function module and name. For instance:

    def getdoc(func):
        func = getattr(xlAlgLib, func)
        return func.__doc__
    

    These work fine if the function is in a different module, but if it is in the same module and I use __main__\ I get an error. For instance:

    def getdoc(func):
        func = getattr(__main__, func)
        return func.__doc__
    

    returns: global name 'main' is not defined ... in getdoc func = getattr(main, func)

    My VBA code is:

    Function xl_GetDoc(Func As String)
    Dim methods As Variant, result As Variant, Rtn As Variant
    Const Modname As String = "xlAlgLib"
        On Error GoTo rtnerr
        Set methods = PyModule(Modname, AddPath:=Path1)
        Set result = PyCall(methods, "getdoc", PyTuple(Func))
        Rtn = PyVar(result)
        xl_GetDoc = Rtn
        Exit Function
    rtnerr:
        xl_GetDoc = Err.Description
    End Function
    

    Any ideas?

     
    • Eric Reynolds

      Eric Reynolds - 2014-07-15

      are you sure that main is always defined in python? I believe that main is actually a special module which is the top-level script, i.e. the one that python is run with. ExcelPython doesn't have this concept since you are not running a single script.

      If you are trying to get a docstring from a function defined in the same module all you need to do is get it from the globals or eval it: eval("myFunction").doc

       
    • Eric Reynolds

      Eric Reynolds - 2014-07-15

      are you sure that main is always defined in python? I believe that
      main is actually a special module which is the top-level script, i.e.
      the one that python is run with. ExcelPython doesn't have this concept,
      because it is a script which gets executed.

      If you are trying to get a docstring from a function defined in the same
      module all you need to do is get it from the globals or eval it:
      eval("myFunction").doc

       

Log in to post a comment.