1 Replies - 6400 Views - Last Post: 16 May 2012 - 08:36 AM Rate Topic: -----

#1 aaron1178  Icon User is offline

  • Dovakiin, Dragonborn
  • member icon

Reputation: 169
  • View blog
  • Posts: 1,298
  • Joined: 22-October 08

Python results in error because of file name

Posted 16 May 2012 - 12:28 AM

Hey guys

This is my first post in the python forums :)

I have a folder callded test with the following contents
*a sub folder
*__init__.py
*test_ninodes.py

Now this is the contents of test_ninodes.py as this is the one file I am calling.
test is the actual folders name
from test import nif_explorer_base

from pyffi.formats.nif import NifFormat

class test_ninodes(nif_explorer_base):
    search_path = "test/nif/base/"
    result_path = "test/nif/ninodes"
    instance = NifFormat.NiNode
    
    def main(self):
        nif_explorer_base.__init__(self)
        nif_explorer_base.nif_explore(self)


test_ninodes.main(test_ninodes)



Now I get a Cannot import name error, but when I change the import to this

from __init__ import nif_explorer_base

from pyffi.formats.nif import NifFormat

class test_ninodes(nif_explorer_base):
    search_path = "test/nif/base/"
    result_path = "test/nif/ninodes"
    instance = NifFormat.NiNode
    
    def main(self):
        nif_explorer_base.__init__(self)
        nif_explorer_base.nif_explore(self)


test_ninodes.main(test_ninodes)



it works as expected. My question is why?

This post has been edited by aaron1178: 16 May 2012 - 12:29 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Python results in error because of file name

#2 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Python results in error because of file name

Posted 16 May 2012 - 08:36 AM

the syntax is:

from module import function/method/class whatever

or

from directory import module

To use the latter approach, you must have a module in that directory called __init__.py, but that module can (and probably should) be empty unless you're using it to aid with exporting modules.

here's an example:

on my desktop I have a directory called test with the contents
  • __init__.py
  • mod.py


__init__.py is literally an empty file.

here is the code for mod.py
def helloWorld():
    print("Yo World!")



On my desktop, I also have a file called tester.py, here is the contents of that:
from test import mod

mod.helloWorld()



You see? test is the directory it's looking in and mod is the module. If I run it, it'll run just fine. If I delete __init__.py, it'll fail because python won't know to look for modules in the test folder.

I hope this helps!


EDIT:
also, if I did decide to put code into the __init__.py module, I could access that by saying import test.

This post has been edited by atraub: 16 May 2012 - 08:41 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1