如何解决和解决python中的“TypeError:'NoneType”对象不可订阅

2024-06-02 23:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码,它使用我命名的get_event_info函数从ticketmasterapi获取数据。随后根据修改后的基于URL的原始身份验证函数代替了原来的修改后的代码。我还向函数添加了几行,用于验证响应状态代码。在进行这些更改之后,代码开始生成以下TypeError

Traceback (most recent call last):
  File "ticketmaster_only_w_headers.py", line 146, in <module>
    for event in ticket_search["_embedded"]["events"].items():
TypeError: 'NoneType' object is not subscriptable

我已经读了很多关于这类错误的文章,但是我仍然不能确定为什么我的代码会在这个实例中产生它。如果能解释一下为什么我的代码会产生这个错误,以及我应该使用什么样的故障排除方法来发现源错误,我将非常感激。我对编程相当满意,但肯定不是专家,所以语言越简单越好。在

(功能定义)

^{pr2}$

(触发错误的代码段)

ticket_search = get_event_info("")

for event in ticket_search["_embedded"]["events"]:
    a = event["id"]
    b = event["name"]
    if "dateTime" in event["dates"]["start"]:
        c = event["dates"]["start"]["dateTime"].replace(
            "T", " ").replace("Z", "")
    else:
        c = "NONE"
    if "end" in event["dates"] and "dateTime" in event["dates"]["end"]:
        j = event["dates"]["end"]["dateTime"].replace(
            "T", " ").replace("Z", "")
    else:
        j = "NONE"

(创建、打开并写入上述代码中使用的缓存的代码)


CACHE_FNAME = "ticketmaster_cache.json"                                         
try:
    cache_file = open(CACHE_FNAME, "r")                                         
    cache_contents = cache_file.read()                                          
    CACHE_DICTION = json.loads(cache_contents)                                  
    cache_file.close()                                                          
except:
    CACHE_DICTION = {}

下面显示的get_event_info函数的前一个版本,它不生成任何TypeError

def get_event_info(search, ticketmaster_key = ticketmaster_key):                                                                                
    if search in CACHE_DICTION:                                         
        d = CACHE_DICTION[search]
    else:                                                                       
        data = requests.get("https://app.ticketmaster.com/discovery/v2/events", 
            params = {"keyword": search, "apikey": ticketmaster_key,            
            "format":"json", "dmaId": "366", "size": 200, "radius": "2"})
        print(data.url)
        d = json.loads(data.text)                                       
        CACHE_DICTION[search] = d                                      
        f = open(CACHE_FNAME, 'w')                                      
        f.write(json.dumps(CACHE_DICTION))                             
        f.close()                                                       
    return d

运行最新版本的代码时看到的回溯和错误消息:

Traceback (most recent call last):
  File "ticketmaster_only_w_headers.py", line 146, in <module>
    for event in ticket_search["_embedded"]["events"]:
TypeError: 'NoneType' object is not subscriptable

Tags: 函数代码ininfoeventjsoncachesearch
2条回答

好吧,解释器显式地告诉您,您正在尝试求值类似于a[i],其中a是{}(而不是预期的类型,如列表或dict)。在您的例子中,它要么是ticket_search本身,要么是{}。在

在任何情况下,如果您可以重新运行代码,那么在ticket_search = get_event_info("")下加一个print(ticket_search)应该可以让一切都清楚。在

每当您有一个可以显式返回None的函数时,您应该始终首先检查返回值:

def func(a):
    if a == 1:
        return list(range(10)) # could return a list
    else:
        return None            # or it could return None

a = 10
f = func(a)

f[1]
# raises TypeError: NoneType is not subscriptable

# check for NoneType first
if f is not None:
    print(f[1])
# otherwise, kick out different result
else:
    print('Got "None" for f!')

# Got "None" for f!

您的ticket_search返回为None,但由于您的for循环正在尝试进行密钥查找,因此失败了,因为None不支持该操作。你的逻辑,从上面来看,应该是这样的:

^{pr2}$

相关问题 更多 >