TypeError: x missing 1 required positional argument: y

Issue

I am trying to import and call a function from my refactor file into my init file. However, when I attempt to call the function in one of the routes, I get this error in the terminal, "TypeError: show_state_locations() missing 1 required positional argument: ‘test_code’"

Here is my code and how I am importing everything:

refactor

import requests
from privateinfo import key

def test_code(state, API_BASE_URL):
    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}

init

from .refactor import test_code


@app.route('/location')
def show_state_locations(test_code):
    """Return selected state from drop down menu"""
    state = request.args.get('state')
    test_code(state, API_BASE_URL)

    return render_template('location.html', latsLngs=latsLngs)

Solution

You are assuming that a name is persisted from one function call to its outer scope:

def f():
    x = 1

f()
print(x)
NameError: name x is not defined

You need to return the value and assign the name to x in the calling scope for this to work

def f():
    return 1

x = f()
x
1

Note that return x doesn’t work either, because it’s the value that’s being returned, not the name:

def f():
    x = 1
    return x

f()
x
# NameError!

x = f()
x
1

The same is happening to latLng:

def test_code():
    latLng = {}

test_code()
latLng = latLng
#NameError!

Change it to

def test_code():
    latLng = {}
    ...
    return latLng

latLng = test_code()
latLng = latLng
# no error

Answered By – C.Nivs

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published