Search code examples
python-2.7pyramid

importing from folder in same package in python


i am using pyramid in views.py

from pyramid.response import Response
from pyramid.view import view_config
import os
import uuid
import shutil
import hashlib
from .service.fun import *

def forservo():
    return "HAppy HERE"


@view_config(route_name='home',request_method='GET')
def home(request):
    return Response('html')

in fun.py

from ..views import *

print forservo()

it throws error saying name 'forservo' is not defined

folder structure is

myapp
  myapp
  service
    __init__.py
    fun.py
  __init__.py
  views.py

Solution

  • You have a cyclic import - fun.py imports from views.py and views.py imports from fun.py.

    In this situation, things happen roughly like this:

    • Python opens views.py and executes it up to the line from .service.fun import *

    • It then has to stop executing views.py and opens fun.py.

    • The very first line of fun.py tells it to stop and import views.py

    • The import statement returns the partially-executed module which does not yet have forservo function defined.

    Cyclic imports can be resolved by moving the common bits of code needed both by fun.py and views.py into a separate module. A less elegant solution is to move some imports below the functions which are causing the cyclic import error or make them local inside a function which needs the import.