0

I'm very new to python, but learning. I have below error in my code, I could solve 1 of the solutions, but I'm not sure is correct.

1. UnboundLocalError: local variable 'newdict' referenced before assignment

In my function I want to copy data to newdict if [elt['id'] for elt in response_json['data']] is higher but I get the error number 1. I then googled and found out that I could add Global newdict, but I am not sure if it is the right of way of expressing variables in Python. I am not sure how I can solve it.

I want to copy only the 'data' key from the nested dictionary response_json, it looks like it is a nested dictionary, so I can compare the 'id' element, because if that's higher than the previous, then I need to do something.

I hope someone can help me.

import json
import pprint, datetime
import numpy as np
import schedule
import time
from http import client

trading_pair_id = 48
offset = 0
limit = 1
newdict = {'id': 0} # <--- Not sure I have done this correct

def trades():
    global newdict  # <--- I'm not sure this is pythonically correct
    # call the API `GET trades` endpoint
    conn = client.HTTPSConnection("trade.blocktrade.com")
    conn.request("GET", "/api/v1/trades/%d?offset=%d&limit=%d" % (trading_pair_id,offset,limit), headers={
    'Content-Type': 'application/json',})
    response = conn.getresponse()
    response_raw = response.read()
    try:
        response_json = json.loads(response_raw)
        pprint.pprint(response_json)
    except:
        print(response_raw)

    print([elt['id'] for elt in response_json['data']])

    if [elt['id'] for elt in response_json['data']] > newdict['id']:
        newdict = dict(response_json)
        print(newdict)
    
schedule.every(5).seconds.do(trades)
  
while True:
    schedule.run_pending()
    time.sleep(1)

Skul9
  • 3
  • 2
Valnurat
  • 71
  • 1
  • 7
  • For a periodic function like this, the global variable is OK. If you were calling the function from other code, you could pass the dict as a parameter. – Barmar Jun 03 '22 at 15:50
  • This doens't look right: `if [elt['id'] for elt in response_json['data']] > newdict['id']` You're comparing a list with a number. – Barmar Jun 03 '22 at 15:52
  • Please make a [mre] with minimal code. This is way too much code and too many imports (some of which are unused) just to cover a scoping issue. It's also not clear what you're trying to accomplish exactly, since ints and lists aren't comparable, so please include expected output and actual output -- or if you get an error, the [full error message with traceback](https://meta.stackoverflow.com/q/359146/4518341), as well as any example input of course. – wjandrea Jun 03 '22 at 15:52
  • FYI you can use `response.json` instead of calling `json.loads()` yourself. – Barmar Jun 03 '22 at 15:53
  • I suspect what you really want is `if any(elt['id'] > newdict['id'] for elt in response_json['data']):` – Barmar Jun 03 '22 at 15:54
  • BTW, [a bare `except` is bad practice](/q/54948548/4518341). Instead, use the specific exception you're expecting like `except ValueError`, or at least `except Exception`. – wjandrea Jun 03 '22 at 15:56
  • @wjandrea - the code here should give some useful output. – Valnurat Jun 03 '22 at 16:03
  • @Valnurat What do you mean? I'm saying *you* need to include the actual output *in the question itself*. You shouldn't expect us to run some non-trivial code just to understand the problem. – wjandrea Jun 03 '22 at 16:05
  • @wjandrea - Ok, sorry. Misunderstod. :) – Valnurat Jun 03 '22 at 16:13

1 Answers1

0

If I understand you correctly, this should be ok

import json
import pprint, datetime
import numpy as np
import time
from http import client

trading_pair_id = 48
offset = 0
limit = 1
newdict = {'id': 0}   # <-- Init variable

def trades(newdict):  # <-- Pass variable to the function
    # call the API `GET trades` endpoint
    conn = client.HTTPSConnection("trade.blocktrade.com")
    conn.request("GET", "/api/v1/trades/%d?offset=%d&limit=%d" % (trading_pair_id,offset,limit), headers={
    'Content-Type': 'application/json',})
    response = conn.getresponse()
    response_raw = response.read()
    try:
        response_json = json.loads(response_raw)
        pprint.pprint(response_json)
        # <-- replace newdict data with newest id
        for elt in response_json['data']:
            if elt['id'] > newdict['id']:
                newdict = elt
                print(newdict)
    except:
        print(response_raw)
        
        
schedule.every(5).seconds.do(trades(newdict))
LiberiFatali
  • 185
  • 11