which_part
which_part

Reputation: 820

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

Upvotes: 1

Views: 112

Answers (2)

Sergey
Sergey

Reputation: 12437

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.

Upvotes: 2

Ravishankar N
Ravishankar N

Reputation: 31

In this folder structure

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

Where views.py has the content

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')

Then import statement in fun.py is:

from myapp.views import forservo()

print forservo()

and this will print "HAppy HERE"

Upvotes: 0

Related Questions