-1

I have two files practice.py and weatherui.py.

I am importing practice in weatherui.py and using its functions. I now want to import weatherui into practice.py and specifically the class UiMainWindow which is in the weatherui.py.

weatherui.py (only the imports are mentioned):

from PyQt5 import QtCore, QtGui, QtWidgets
import practice

information = practice.get_weather_data(practice.generate_url(practice.new_url, practice.lat, practice.lon))
print(information)

class Ui_MainWindow(object):

practice.py:

from datetime import datetime
import requests
import mysql.connector
from weatherui import Ui_MainWindow     //this causes the traceback 

url = 'https://api.openweathermap.org/data/2.5/weather?q='
new_url = 'https://api.openweathermap.org/data/2.5/onecall?'
city_input = Ui_MainWindow.clickMethod().capitalize()
apiKey = '82e2832b8f0eac296c9e75cb93d03317'
theUrl = url + city_input + '&appid=' + apiKey;

r = requests.get(theUrl)
data = r.json()
lat = data['coord']['lat']
lon = data['coord']['lon']
city_name = data['name']


def generate_url(url, lat, lon):
    return url + 'lat=' + str(lat) + '&lon=' + str(lon) + '&exclude={part}' + '&appid=' + apiKey
    

def get_weather_data(url):
    r = requests.get(url)
    data = r.json()
    main_desc = data['current']['weather'][0]['main']
    temp_main = data['current']['temp']
    feels_like = data['current']['feels_like']
    pressure = data['current']['pressure']
    humidity = data['current']['humidity']
    wind_speed = data['current']['wind_speed']

    daily = data['daily']
    dt1 = datetime.fromtimestamp(daily[1]['dt']).strftime('%d-%m-%Y')
    dt2 = datetime.fromtimestamp(daily[2]['dt']).strftime('%d-%m-%Y')
    dt3 = datetime.fromtimestamp(daily[3]['dt']).strftime('%d-%m-%Y')
    dt4 = datetime.fromtimestamp(daily[4]['dt']).strftime('%d-%m-%Y')
    dt5 = datetime.fromtimestamp(daily[5]['dt']).strftime('%d-%m-%Y')
    dt6 = datetime.fromtimestamp(daily[6]['dt']).strftime('%d-%m-%Y')
    dt7 = datetime.fromtimestamp(daily[7]['dt']).strftime('%d-%m-%Y')

    icon_main = data['current']['weather'][0]['icon']
    icon1 = daily[1]['weather'][0]['icon']
    icon2 = daily[2]['weather'][0]['icon']
    icon3 = daily[3]['weather'][0]['icon']
    icon4 = daily[4]['weather'][0]['icon']
    icon5 = daily[5]['weather'][0]['icon']
    icon6 = daily[6]['weather'][0]['icon']
    icon7 = daily[7]['weather'][0]['icon']

    temp1 = daily[1]['temp']['day']
    temp2 = daily[2]['temp']['day']
    temp3 = daily[3]['temp']['day']
    temp4 = daily[4]['temp']['day']
    temp5 = daily[5]['temp']['day']
    temp6 = daily[6]['temp']['day']
    temp7 = daily[7]['temp']['day']
    return temp_main, main_desc, icon_main+'.png', feels_like, pressure, humidity, wind_speed


def update_database(weather_information):
    mydb = mysql.connector.connect(host="localhost", user="root", passwd="adarsh", database="example")
    mycursor = mydb.cursor()
    sql = "REPLACE INTO weather_information (city, temperature_main, descp, icon, feels_like, pressure, humidity, wind_speed) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
    mycursor.execute(sql, weather_information)
    mydb.commit()

def fetch_to_database():
    mydb = mysql.connector.connect(host="localhost", user="root", passwd="adarsh", database="example")
    mycursor = mydb.cursor(buffered=True)
    sql =  """SELECT * FROM weather_information WHERE city = %s"""
    mycursor.execute(sql, (city_input,))
    record = mycursor.fetchall()
    # print(record)
    for row in record:
        city, temp_main, descp, icon, feels_like, pressure, humidity, wind_speed = row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7]
    mydb.commit()
    return city, temp_main, descp, icon, feels_like, pressure, humidity, wind_speed

When I run above code I get this traceback:

enter image description here

I am unable to do so no matter what I try. First I thought it is a problem of circular dependency and I used all the recommended solutions to eliminate it but to no avail.

Erros i came across:

  1. AttributeError: 'module' object has no attribute
  2. Import Name Error

Note: weatherui.py is class based and practice.py is function based (no classes in practice.py)

Any help would be appreciated.

Albert
  • 53
  • 5
  • 1
    You should [edit] your question to include the full error traceback of each error, as that contains valuable information. For example, in the case of `AttributeError: 'module' object has no attribute ...` have you verified that the module _does_ in fact have the attribute mentioned? – G. Anderson Feb 28 '22 at 17:38
  • "Unable to do so" doesn't help us understand the problem. Please explain what actually happens. – Ilya Feb 28 '22 at 17:52
  • I think this is because of circular dependant imports. Please go through [this](https://stackoverflow.com/questions/9252543/importerror-cannot-import-name-x) link, it might help you. – Vishwa Mittar Feb 28 '22 at 17:54
  • @G.Anderson as advised by you, I have edited the code and included the traceback and also some additional information – Albert Feb 28 '22 at 18:17
  • Agree with @VishwaMittar on the circular import. Look at your traceback: "from weatherui import Ui_MainWindow; import practice; from weatherui import Ui_MainWindow". weather can't run because it first has to import practice, practice can't finish importing because it first has to import weather, which first has to import practice... how would python resolve this? Have you considered having `weather` and `practice` separate, and import both into a third script to actually use? – G. Anderson Feb 28 '22 at 18:43
  • @G.Anderson okay so I created mid.py and then imported both weather and practice into in. I made two function both of which return exactly what I need from practice and weather respectively. You can check the question again for the code and the new errors – Albert Feb 28 '22 at 18:54
  • 1
    You've done the same thing, `practice` is importing `mid`, and `mid` is importing `practice`. `practice` and `weather` need to not depend on anything else, and `mid` needs to import from them – G. Anderson Feb 28 '22 at 19:06
  • 1
    The problem is circular imports as @G.Anderson said, but I disagree on how to fix it. `mid` doesn't need any imports. If you want to pass the functions some values, pass them as arguments. Then have `weather` and `practice` import `mid`, and then you should be able to do `mid.info()` and `mid.inp()` no problem – Pranav Hosangadi Feb 28 '22 at 19:08
  • @PranavHosangadi I really appreciaate your efforts but I cannot understand how am I supposed to pass valyes to the functions of mid without actually importing the values in mid. – Albert Feb 28 '22 at 19:19
  • `def info(whatever, arguments, info, needs)` – Pranav Hosangadi Feb 28 '22 at 19:23
  • @PranavHosangadi info needs to access the practice file and the return value of info will be used in weather. So if I do not import practice in mid for info to use, I will have to import practice in weather when I call info in it. Make sense? – Albert Feb 28 '22 at 19:32
  • Unfortunately the scope of this question keeps expanding. In general, we can't write your code for you, beyond specific answers to specific questions. I would recommend that you step back for a moment, look at how your code is currently organized, and perhaps try rebuilding it from scratch, keeping in mind: You cannot import b into a, when you rely on importing a into b. Maybe that means (re)defining `clickMethod().capitalize()` inside of `practice` instead of importing it. Maybe that means a separate `constants.py` where you don't import and only define (if that's your sticking point) – G. Anderson Mar 01 '22 at 17:08
  • 1
    In general, myself and @PranavHosangadi have told you why your current code isn't working, and how to resolve the error, but I think your whole project is too broad for us to be able to provide meaningful help, given that we can't see the bigger picture. We truly want to help, so after you re-organize your code, please come back and ask again if you have a _specific_ question with a [mcve] – G. Anderson Mar 01 '22 at 17:09
  • 1
    @G.Anderson thank you for your time. I genuinely appreciate your efforts. I will refactor my code and get back to you.. – Albert Mar 02 '22 at 18:26

1 Answers1

1

Taking a step back, it's still not clear why weatherui needs to import practice

Without knowing what many of your functions actually do, would something like this not work?

weatherui.py

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1920, 1080)
        MainWindow.setMinimumSize(QtCore.QSize(1920, 1080))
        ...

practice.py

from datetime import datetime
import requests
import mysql.connector
from weatherui import Ui_MainWindow

def get_weather_data():
    #whatever this does
    pass

def generate_url(url, lat,lon):
    #whatever this does
    pass

def info(url, lat, lon):
    #assuming there's some reason we have to pass these args through, given some code we haven't seen
    url= generate_url(new_url, lat, lon)
    data= get_weather_data(url)
    return get_weather_data(practice.generate_url(practice.new_url, practice.lat, practice.lon))

def inp():
    return Ui_MainWindow.clickMethod().capitalize()


url = 'https://api.openweathermap.org/data/2.5/weather?q='
new_url = 'https://api.openweathermap.org/data/2.5/onecall?'
lat=None
lon=None

city = inp()
city_info = info(new_url, let, lon)
G. Anderson
  • 5,815
  • 2
  • 14
  • 21
  • The information that you are returning inside `info()` which is declared in ractice.py is needed inside weatherui beacuse weatherui contains the ui elemets that I will use to show the data. Thus I will need practice to be imported inside weatherui – Albert Mar 01 '22 at 07:24
  • I have included the entire practice.py in the question for you to go through. For weather ui it has a class `Ui_MainWindow` which has a method `clickMethod()` (that returns the value passed inside an input text field) whos return value I need inside practice.py to initiate the api call. – Albert Mar 01 '22 at 07:29