0

I am refactoring/moving some code in my init file for better readability and to manage my app's main file. As a result, I'm attempting to import a function from the refactor file into init, but I continue to get this error,

ImportError: cannot import name 'test_state_locations' from 'app.refactor'

Here is how I am importing:

# File: __init__.py

from .refactor import test_state_locations
# File: refactor.py

import requests
from privateinfo import key
from .__init__ import API_BASE_URL

def test_state_locations(state):
    url = f'https://covid-19-testing.github.io/locations/{state.lower()}/complete.json'
    res = requests.get(url)
    testing_data = res.json()
    latsLngs = {}
    for obj in testing_data:
          if obj["physical_address"]:

            for o in obj["physical_address"]:
                    addy = o["address_1"] 
                    city = o["city"]
                    phone = obj["phones"][0]["number"]

            location = f'{addy} {city}'
            res2 = requests.get(API_BASE_URL,
                                params={'key': key, 'location': location})

            location_coordinates = res2.json()
            lat = location_coordinates["results"][0]["locations"][0]["latLng"]["lat"]
            lng = location_coordinates["results"][0]["locations"][0]["latLng"]["lng"]
            latsLngs[location] = {'lat': lat, 'lng': lng, 'place': location, 'phone': phone}

Here is a photo of my app's directory: enter image description here

Aven Desta
  • 2,114
  • 12
  • 27
rudehlabya
  • 109
  • 1
  • 8

2 Answers2

3

Your refactor.py import something from __init__.py; It makes circular import issue.


#from .__init__ import API_BASE_URL
Mont
  • 164
  • 1
  • 4
2

You are making a circular import. In __init__.py, you're importing refactor and circularly in refactor.py you're using __init__

Here is how python deals with your code. It first looks at refactor.py and tries to import __init__. But to import __init__, python has to run the file __init__.py. But again __init__.py requires refactor, and has to go back to refactor.py. At this point python stops the loop and raises Import Error.

Python import breaks if your import is circular. Read here for more.

If you're working with Flask framework, here is a Youtube tutorial to help you structure your modules to avoid circular import

Aven Desta
  • 2,114
  • 12
  • 27