main.py cannot read module called by inside other module

I’m trying out Google’s geo APIs and to try and respect good practice I’m trying to keep my api key out of my GitHub repo by putting it in a file (api_keys.py).

coordinates_api.py calls api_keys.py with import api_keys to retrieve the key and call the APIs, and when testing coordinates_api.py everything works fine and I get my coordinates printed as I expect.

When I test main.py though, which calls coordinates_api.py, I get the error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Traceback (most recent call last):
File "c:UsersmeDocumentsProjectsGitProjectNamesrcmain.py", line 1, in <module>
from apis import *
File "c:UsersmeDocumentsProjectsGitProjectNamesrcapiscoordinates_api.py", line 2, in <module>
import api_keys
ModuleNotFoundError: No module named 'api_keys'
</code>
<code>Traceback (most recent call last): File "c:UsersmeDocumentsProjectsGitProjectNamesrcmain.py", line 1, in <module> from apis import * File "c:UsersmeDocumentsProjectsGitProjectNamesrcapiscoordinates_api.py", line 2, in <module> import api_keys ModuleNotFoundError: No module named 'api_keys' </code>
Traceback (most recent call last):
  File "c:UsersmeDocumentsProjectsGitProjectNamesrcmain.py", line 1, in <module>
    from apis import *
  File "c:UsersmeDocumentsProjectsGitProjectNamesrcapiscoordinates_api.py", line 2, in <module>
    import api_keys
ModuleNotFoundError: No module named 'api_keys'

I don’t understand why my api_keys module is not recognized by main.py

Here’s the code for coordinates_api.py:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import requests
import api_keys
class CoordinatesAPI:
def __init__(self, api_key=None):
self.api_key = api_keys.geo
def get_coordinates(self, address):
base_url = "https://maps.googleapis.com/maps/api/geocode/json"
params = {
"address": address,
"key": self.api_key
}
response = requests.get(base_url, params=params)
if response.status_code == 200:
data = response.json()
if data['status'] == 'OK':
location = data['results'][0]['geometry']['location']
return location['lat'], location['lng']
else:
raise Exception(f"Error from API: {data['status']}")
else:
raise Exception(f"HTTP error: {response.status_code}")
</code>
<code>import requests import api_keys class CoordinatesAPI: def __init__(self, api_key=None): self.api_key = api_keys.geo def get_coordinates(self, address): base_url = "https://maps.googleapis.com/maps/api/geocode/json" params = { "address": address, "key": self.api_key } response = requests.get(base_url, params=params) if response.status_code == 200: data = response.json() if data['status'] == 'OK': location = data['results'][0]['geometry']['location'] return location['lat'], location['lng'] else: raise Exception(f"Error from API: {data['status']}") else: raise Exception(f"HTTP error: {response.status_code}") </code>
import requests
import api_keys

class CoordinatesAPI:
    def __init__(self, api_key=None):
        self.api_key = api_keys.geo

    def get_coordinates(self, address):
        base_url = "https://maps.googleapis.com/maps/api/geocode/json"
        params = {
            "address": address,
            "key": self.api_key
        }
        response = requests.get(base_url, params=params)
        if response.status_code == 200:
            data = response.json()
            if data['status'] == 'OK':
                location = data['results'][0]['geometry']['location']
                return location['lat'], location['lng']
            else:
                raise Exception(f"Error from API: {data['status']}")
        else:
            raise Exception(f"HTTP error: {response.status_code}")

And for main.py:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from apis import coordinates_api
if __name__ == "__main__":
address = "1600 Amphitheatre Parkway, Mountain View, CA"
CA1 = coordinates_api.CoordinatesAPI()
lat, lng = CA1.get_coordinates(address)
print(f"Latitude: {lat}, Longitude: {lng}")
</code>
<code>from apis import coordinates_api if __name__ == "__main__": address = "1600 Amphitheatre Parkway, Mountain View, CA" CA1 = coordinates_api.CoordinatesAPI() lat, lng = CA1.get_coordinates(address) print(f"Latitude: {lat}, Longitude: {lng}") </code>
from apis import coordinates_api

if __name__ == "__main__":
    address = "1600 Amphitheatre Parkway, Mountain View, CA"
    CA1 = coordinates_api.CoordinatesAPI()
    lat, lng = CA1.get_coordinates(address)
    print(f"Latitude: {lat}, Longitude: {lng}")

(Here I also tried playing a bit with the import but also e.g. from apis import * gives the same error. Rather than doing trial and error I would like to properly understand what I’m missing here)

This is what my tree looks like:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>│ main.py
├───apis
│ │ api_keys.py
│ │ coordinates_api.py
│ │ __init__.py
</code>
<code>│ main.py │ ├───apis │ │ api_keys.py │ │ coordinates_api.py │ │ __init__.py </code>
│   main.py
│
├───apis
│   │   api_keys.py
│   │   coordinates_api.py
│   │   __init__.py

New contributor

user24196311 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

If you always mean to use your package from outside of its folder, you can simply substitute import api_keys with from apis import api_keys or from . import api_keys.

Otherwise you can can add apis to PYTHONPATH environment variable, so that modules can be searched inside this folder, without having to know from where the script is run.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật