__init__.py question

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

    #1

    __init__.py question

    Ok, I have the following directory structure

    C:\pycode
    --> blah.py
    --> mynewdir
    --> __init__.py
    --> abc.py

    [[ C:\pycode\mynew dir\abc.py ]]

    def doFoo():
    print "hi"

    def doBar():
    print "bye"

    [[ C:\pycode\mynew dir\__init__.py ]]

    from mynewdir import *

    [[ C:\pycode\blah. py ]]

    ????

    what do i import in blah.py so that I can accesss, abc.doFoo() ?

    thanks

  • gry@ll.mit.edu

    #2
    Re: __init__.py question

    from mynewdir import abc
    abc.doFoo()

    or

    import mynewdir.abc
    newdir.abc.doFo o()

    Comment

    • Terry Hancock

      #3
      Re: __init__.py question

      On Friday 22 April 2005 07:19 am, codecraig wrote:[color=blue]
      > Ok, I have the following directory structure
      >
      > C:\pycode
      > --> blah.py
      > --> mynewdir
      > --> __init__.py
      > --> abc.py
      >
      > [[ C:\pycode\mynew dir\abc.py ]]
      >
      > def doFoo():
      > print "hi"
      >
      > def doBar():
      > print "bye"
      >
      > [[ C:\pycode\mynew dir\__init__.py ]]
      >
      > from mynewdir import *[/color]

      This didn't work, did it? There is no module
      "mynewdir.p y" nor a package "mynewdir" in
      the "mynewdir" directory, and I don't think import
      will search up to find the container.

      I suspect you meant that __init__.py says:

      from abc import *
      [color=blue]
      > [[ C:\pycode\blah. py ]]
      >
      > ????
      >
      > what do i import in blah.py so that I can accesss,[/color]
      abc.doFoo() ?

      Assuming the above, and that you want to access
      it as you have written it, that would be:

      from mynewdir import abc

      Note that in order to use this form, you don't have
      to have *anything* in mynewdir/__init__.py --- it can
      be an empty file, as long as it exists.

      You only need to use an import in __init__.py if you
      want it to automatically run when you import the
      package.

      E.g. if you did:

      import mynewdir

      You could access your function as:

      mynewdir.abc.do Foo

      (which requires the import statement in __init__.py).

      Cheers,
      Terry


      --
      Terry Hancock ( hancock at anansispacework s.com )
      Anansi Spaceworks http://www.anansispaceworks.com

      Comment

      Working...