Неопределенная переменная с использованием декораторов - PullRequest
0 голосов
/ 03 мая 2018

Я пытаюсь написать код, который позволит человеку вводить либо координаты, либо местоположение, который затем будет возвращать либо название места, либо координаты места, очевидно, в зависимости от того, какой пользователь решил ввести первым. Ошибка, с которой я столкнулся, следующая ошибка: NameError: name 'search_lan' is not defined Ошибка появляется под some_funcion() на url переменная

import json
import requests

def my_decorator(some_function):
    def wrapper():
        question = input("Would you like to input coordinates or location?")
        if question == 'coordinates':
            search_lan = input("Input latitude: ")
            search_lon = input("Input longtitude: ")
        elif question == 'location':
            search_place = input("Input address: ")
        else:
            print("Wrong input")
        some_function()

        return search_place, search_lan, search_lon
    return wrapper

api_key = 'api_key_here'




@my_decorator
def some_function():
   url = requests.get('https://maps.googleapis.com/maps/api/geocode/json? 
   latlng={},{}&key={}'.format(search_lan,search_lon,api_key))

   data = json.loads(url.content)

   formatted_address = data['results'][0]['formatted_address']
   print(formatted_address)

some_function()

Ответы [ 2 ]

0 голосов
/ 03 мая 2018

Позволяет разбить области действия вашего кода.

# Scope: global
import json
import requests

def my_decorator(some_function):
    # Scope: global > my_decorator
    def wrapper():
        # Scope: global > my_decorator > wrapper
        question = input("Would you like to input coordinates or location?")
        if question == 'coordinates':
            search_lan = input("Input latitude: ")
            search_lon = input("Input longtitude: ")
        elif question == 'location':
            search_place = input("Input address: ")
        else:
            print("Wrong input")
        some_function()

        return search_place, search_lan, search_lon
    return wrapper

api_key = 'api_key_here'


@my_decorator
def some_function():
    # Scope: global > some_function
    url = requests.get('https://maps.googleapis.com/maps/api/geocode/json? 
    latlng={},{}&key={}'.format(search_lan,search_lon,api_key))

    data = json.loads(url.content)

    formatted_address = data['results'][0]['formatted_address']
    print(formatted_address)

some_function()

Переменные search_lan и search_lon (иногда) определяются в области действия global> my_decorator> wrapper . Вы пытаетесь использовать их в global> some_function scope , которая не является дочерней областью первой. Это означает, что эти переменные не определены.

Что вы, вероятно, хотите сделать, это передать переменные, определенные в оболочке декоратора, в декорированную функцию.

import json
import requests

# fn is the decorated function, in this case fn.
def my_decorator(fn):
    def wrapper():
        question = input("Would you like to input coordinates or location?")
        # Make sure these variables are always defined, as they are used later.
        search_lan = None
        search_lon = None

        if question == 'coordinates':
            search_lan = input("Input latitude: ")
            search_lon = input("Input longtitude: ")
        elif question == 'location':
            # This is not handled, but you’ll get the idea.
            search_place = input("Input address: ")
        else:
            print("Wrong input")
        return fn(search_lan, search_lon)
    return wrapper

api_key = 'api_key_here'


# search_lan and search_lon are passed by my_decorator.
@my_decorator
def some_function(search_lan, search_lon):
    url = requests.get('https://maps.googleapis.com/maps/api/geocode/json? 
    latlng={},{}&key={}'.format(search_lan,search_lon,api_key))

    data = json.loads(url.content)

    formatted_address = data['results'][0]['formatted_address']
    print(formatted_address)

some_function()
0 голосов
/ 03 мая 2018

Проблема в search_lan = input("Input latitude: ") не всегда будет выполняться, например, если они вводят location или неверный ввод.

...