Tricky import question.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • David Poundall

    #1

    Tricky import question.

    importedfiles = {}
    for f in FileList
    f2 = f.split('.')[0] # strip the .py, .pyc
    __import__(f2)
    s2 = f2+'.main()' # main is the top file in each import
    c = compile(s2, '', 'eval')
    importedfiles[f2] = eval(c)

    'importedfiles' should hold an object reference to the main() function
    within each imported file.

    The problem is, the import function works but I can't get the object
    reference into the imortedfiles dictionary object. the code keeps
    telling me

    NameError: name 'C1_Dosing' is not defined.

    in this instance C1_Dosing is the first file name in the filelist. The
    import worked, why not the compile ??

    TIA.

  • Fredrik Lundh

    #2
    Re: Tricky import question.

    David Poundall wrote:
    [color=blue]
    > importedfiles = {}
    > for f in FileList
    > f2 = f.split('.')[0] # strip the .py, .pyc
    > __import__(f2)
    > s2 = f2+'.main()' # main is the top file in each import
    > c = compile(s2, '', 'eval')
    > importedfiles[f2] = eval(c)
    >
    > 'importedfiles' should hold an object reference to the main() function
    > within each imported file.
    >
    > The problem is, the import function works but I can't get the object
    > reference into the imortedfiles dictionary object. the code keeps
    > telling me
    >
    > NameError: name 'C1_Dosing' is not defined.
    >
    > in this instance C1_Dosing is the first file name in the filelist. The
    > import worked, why not the compile ??[/color]

    because your __import__ statement didn't assign the returned module
    to anything, so there's no C1_Dosing in the current namespace.

    assuming that the main function in each module returns something that
    you want to store in the importedfiles dictionary, here's a better way to
    do it:

    m = __import__(f2)
    importedfiles[f2] = getattr(m, "main")()

    tweak as necessary.

    </F>



    Comment

    • David Poundall

      #3
      Re: Tricky import question.

      Sadly I get this reply when I try that.

      AttributeError: 'module' object has no attribute 'main'

      I am getting the impression that the value returned from the
      __import__() function is only a string reference NOT an object.

      I am going to have a go at trying this with the imp' module as that
      specifically mentions that an object is returned.

      Comment

      • David Poundall

        #4
        Re: Tricky import question.

        This worked ...

        def my_import(name) :
        mod = __import__(name )
        components = name.split('.')
        for comp in components[1:]:
        mod = getattr(mod, comp)
        return mod

        for reasons given here...



        Comment

        • Bengt Richter

          #5
          Re: Tricky import question.

          On 25 Oct 2005 06:39:15 -0700, "David Poundall" <david@jotax.co m> wrote:
          [color=blue]
          >importedfile s = {}
          >for f in FileList
          > f2 = f.split('.')[0] # strip the .py, .pyc[/color]
          importedfiles[f2] = __import__(f2). main
          # it sounds like all you want is the above (untested ;-), or
          # use __import__(f2). main() if you actually want the _result_ returned by main

          Either way, you don't need the following[color=blue]
          > __import__(f2)
          > s2 = f2+'.main()' # main is the top file in each import
          > c = compile(s2, '', 'eval')
          > importedfiles[f2] = eval(c)
          >
          >'importedfiles ' should hold an object reference to the main() function
          >within each imported file.[/color]
          Do you want a reference to the function, or the result of calling the function?
          If you want a reference to the function itself, you should leave off the () after main,
          otherwise you will execute the function.
          [color=blue]
          >
          >The problem is, the import function works but I can't get the object
          >reference into the imortedfiles dictionary object. the code keeps
          >telling me
          >
          >NameError: name 'C1_Dosing' is not defined.[/color]
          probably your first file is C1_Dosing.py (or some other extension after the '.')
          so f2 becomes 'C1_Dosing' and s2 becomes 'C1_Dosing.main ()' and you compile that
          into code bound to c, and when you try to eval(c), it tries to find C1_Dosing in
          the current environment, et voila! you have the error.

          When confronted with mysteries such as presented by your code results, I suggest
          you intruduce print statements to verify what you are assuming about what it is doing.
          E.g., you could print repr(f2) after assignment, and after the __import__ if you thought
          it was going to do something to f2 in the local name space, and repr(s2) after the assignment,
          etc. to see if I guessed right. Or a quick line to clone for a snapshot of local varibles
          at different points might be (untested)
          print '\n'.join('%15s : %s'%(k, repr(v)[:60]) for k,v in sorted(locals() .items()))
          [color=blue]
          >
          >in this instance C1_Dosing is the first file name in the filelist. The
          >import worked, why not the compile ??[/color]
          I think the compile did work. But your code didn't produce a binding for the name
          'C1_Dosing' which the code c was looking for when eval(c) was called. If you wanted to
          make your code work, perhaps replacing (untested)
          __import__(f2)
          with
          exec '%s = __import__(f2)' %f2 # bind imported module to name specified by f2 string
          might have got by the error in eval (c), but I suspect you would want to leave the () off
          the .main in any case. And why go through all that rigamarole?
          [color=blue]
          >
          >TIA.
          >[/color]
          Try it both ways and report back what you found out ;-)

          Regards,
          Bengt Richter

          Comment

          • Bengt Richter

            #6
            Re: Tricky import question.

            On 25 Oct 2005 08:51:08 -0700, "David Poundall" <david@jotax.co m> wrote:
            [color=blue]
            >This worked ...
            >
            >def my_import(name) :
            > mod = __import__(name )
            > components = name.split('.')
            > for comp in components[1:]:
            > mod = getattr(mod, comp)
            > return mod
            >
            >for reasons given here...
            >
            >http://www.python.org/doc/2.3.5/lib/built-in-funcs.html
            >[/color]
            Aha. You didn't mention multi-dot names ;-)
            But was that the real problem? Your original code
            wasn't using anything corresponding to mod above.

            Regards,
            Bengt Richter

            Comment

            • David Poundall

              #7
              Re: Tricky import question.

              All I was trying to do with my feeble code attempt, was to return a
              reference to the imported module so that I could do...

              result = instanceref.mai n()

              where main was a function within the import.

              Having glanced at the code in the import section of the help files all
              morning, when I actually sat down and read it it turned out the example
              code was what I needed.

              Its always the way.

              Many thanks for taking time out to reply Bengt.

              Comment

              • David Poundall

                #8
                Re: Tricky import question.

                repr() is a new one on me I am afraid, and I have yet to achieve any
                decent competance with global and local lists.

                As you probaly noticed earlier, I managed to bungle my way through this
                time. However, I will log this thread away for when I next get stuck
                with a bindings.

                Thank you Bengt :-)

                Comment

                Working...