标签归档:nonetype

TypeError:“ NoneType”对象在Python中不可迭代

问题:TypeError:“ NoneType”对象在Python中不可迭代

错误TypeError: 'NoneType' object is not iterable是什么意思?

我在以下Python代码上得到它:

def write_file(data, filename): # creates file and writes list to it
  with open(filename, 'wb') as outfile:
    writer = csv.writer(outfile)
    for row in data: # ABOVE ERROR IS THROWN HERE
      writer.writerow(row)

What does error TypeError: 'NoneType' object is not iterable mean?

I am getting it on this Python code:

def write_file(data, filename): # creates file and writes list to it
  with open(filename, 'wb') as outfile:
    writer = csv.writer(outfile)
    for row in data: # ABOVE ERROR IS THROWN HERE
      writer.writerow(row)

回答 0

这表示datais 的值None

It means the value of data is None.


回答 1

错误说明:“ NoneType”对象不可迭代

在python2中,NoneType是None的类型。在Python3中,NoneType是None的类,例如:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

遍历具有值None的变量失败:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

Python方法如果不返回值,则返回NoneType:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

您需要像这样检查NoneType的循环结构:

a = None 
print(a is None)              #prints True
print(a is not None)          #prints False
print(a == None)              #prints True
print(a != None)              #prints False
print(isinstance(a, object))  #prints True
print(isinstance(a, str))     #prints False

Guido说只用于is检查,None因为is它对身份检查更可靠。不要使用相等运算,因为那些运算会加剧自身的泡沫。 Python的编码样式指南-PEP-008

类型是偷偷摸摸的,可以从lambdas偷偷溜走:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType不是有效的关键字:

a = NoneType     #NameError: name 'NoneType' is not defined

None和字符串的串联:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

这里发生了什么?

Python的解释器将您的代码转换为pyc字节码。Python虚拟机处理了字节码,它遇到了一个循环结构,该结构表示对包含None的变量进行迭代。通过__iter__在None上调用该方法来执行该操作。

None没有__iter__定义方法,因此Python的虚拟机会告诉您所看到的内容:NoneType没有__iter__方法。

这就是为什么Python的鸭式思维被认为是不好的。程序员使用变量进行了完全合理的操作,在运行时它被None污染,python虚拟机试图继续运行,并在地毯上吐出一堆无关紧要的废话。

Java或C ++没有这些问题,因为不允许您编译此类程序,因为您没有定义发生None时的处理方法。Python允许您执行很多在特殊情况下无法预期的工作,从而为程序员提供了很多上锁的绳索。Python是一个肯定的人,当它像Java和C ++那样阻止您伤害自己时,说是肯定的先生。

Explanation of error: ‘NoneType’ object is not iterable

In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

Iterating over a variable that has value None fails:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

Python methods return NoneType if they don’t return a value:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

You need to check your looping constructs for NoneType like this:

a = None 
print(a is None)              #prints True
print(a is not None)          #prints False
print(a == None)              #prints True
print(a != None)              #prints False
print(isinstance(a, object))  #prints True
print(isinstance(a, str))     #prints False

Guido says only use is to check for None because is is more robust to identity checking. Don’t use equality operations because those can spit bubble-up implementationitis of their own. Python’s Coding Style Guidelines – PEP-008

NoneTypes are Sneaky, and can sneak in from lambdas:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType is not a valid keyword:

a = NoneType     #NameError: name 'NoneType' is not defined

Concatenation of None and a string:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

What’s going on here?

Python’s interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__ method on the None.

None has no __iter__ method defined, so Python’s virtual machine tells you what it sees: that NoneType has no __iter__ method.

This is why Python’s duck-typing ideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.

Java or C++ doesn’t have these problems because such a program wouldn’t be allowed to compile since you haven’t defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.


回答 2

代码:for row in data:
错误消息:TypeError: 'NoneType' object is not iterable

它在抱怨哪个对象?选择两个,rowdata。在中for row in data,哪个需要迭代?只有data

有什么问题data吗?其类型为NoneType。只有None类型NoneType。这样data is None

您可以在IDE中进行验证,也可以通过print "data is", repr(data)for语句之前插入例如并重新运行来进行验证。

考虑下一步需要做什么: 应如何表示“无数据”?我们写一个空文件吗?我们是否引发异常或记录警告或保持沉默?

Code: for row in data:
Error message: TypeError: 'NoneType' object is not iterable

Which object is it complaining about? Choice of two, row and data. In for row in data, which needs to be iterable? Only data.

What’s the problem with data? Its type is NoneType. Only None has type NoneType. So data is None.

You can verify this in an IDE, or by inserting e.g. print "data is", repr(data) before the for statement, and re-running.

Think about what you need to do next: How should “no data” be represented? Do we write an empty file? Do we raise an exception or log a warning or keep silent?


回答 3

可能产生此错误的另一件事是,当您设置的内容等于从函数返回的值时,却忘记了实际返回任何内容。

例:

def foo(dict_of_dicts):
    for key, row in dict_of_dicts.items():
        for key, inner_row in row.items():
            Do SomeThing
    #Whoops, forgot to return all my stuff

return1, return2, return3 = foo(dict_of_dicts)

这是一个很难发现的错误,因为如果在一次迭代中行变量碰巧为None,那么也会产生该错误。发现它的方法是跟踪在最后一行而不是在函数内部失败。

如果您仅从函数返回一个变量,则不确定是否会产生错误…我怀疑错误“’NoneType’对象在Python中不可迭代”在这种情况下实际上意味着“嘿,我正在尝试遍历返回值以按顺序将它们分配给这三个变量,但我只得到None进行遍历”

Another thing that can produce this error is when you are setting something equal to the return from a function, but forgot to actually return anything.

Example:

def foo(dict_of_dicts):
    for key, row in dict_of_dicts.items():
        for key, inner_row in row.items():
            Do SomeThing
    #Whoops, forgot to return all my stuff

return1, return2, return3 = foo(dict_of_dicts)

This is a little bit of a tough error to spot because the error can also be produced if the row variable happens to be None on one of the iterations. The way to spot it is that the trace fails on the last line and not inside the function.

If your only returning one variable from a function, I am not sure if the error would be produced… I suspect error “‘NoneType’ object is not iterable in Python” in this case is actually implying “Hey, I’m trying to iterate over the return values to assign them to these three variables in order but I’m only getting None to iterate over”


回答 4

这意味着数据变量正在传递None(类型为NoneType),等效于没有。因此,正如您正在尝试的那样,它不能作为列表进行迭代。

It means that the data variable is passing None (which is type NoneType), its equivalent for nothing. So it can’t be iterable as a list, as you are trying to do.


回答 5

您正在使用以下参数调用write_file:

write_file(foo, bar)

但是您没有正确定义’foo’,或者您的代码中有错字,以便它创建一个新的空变量并将其传入。

You’re calling write_file with arguments like this:

write_file(foo, bar)

But you haven’t defined ‘foo’ correctly, or you have a typo in your code so that it’s creating a new empty variable and passing it in.


回答 6

对我来说,这是戴Groovy帽子而不是Python 3的情况。

returndef函数末尾忘记了关键字。

几个月没有认真编写Python 3。我以为是按照Groovy方式返回例程中评估的最后一条语句。

进行了几次迭代,查看堆栈跟踪,插入try: ... except TypeError: ...块调试/单步执行代码以找出错误所在。

该消息的解决方案当然并没有使错误跳出我的嘴。

For me it was a case of having my Groovy hat on instead of the Python 3 one.

Forgot the return keyword at the end of a def function.

Had not been coding Python 3 in earnest for a couple of months. Was thinking last statement evaluated in routine was being returned per the Groovy (or Rust) way.

Took a few iterations, looking at the stack trace, inserting try: ... except TypeError: ... block debugging/stepping thru code to figure out what was wrong.

The solution for the message certainly did not make the error jump out at me.


Python None比较:我应该使用“ is”还是==?

问题:Python None比较:我应该使用“ is”还是==?

比较时我的编辑会警告我my_var == None,但使用时不会警告my_var is None

我在Python Shell中进行了测试,并确定两者都是有效的语法,但我的编辑器似乎在说这my_var is None是首选。

是这样吗?如果是这样,为什么?

My editor warns me when I compare my_var == None, but no warning when I use my_var is None.

I did a test in the Python shell and determined both are valid syntax, but my editor seems to be saying that my_var is None is preferred.

Is this the case, and if so, why?


回答 0

摘要:

使用is时要核对对象的身份(如检查,看看是否varNone)。使用==时要检查的平等(例如是var等于3?)。

说明:

您可以在其中my_var == None返回的自定义类True

例如:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is检查对象身份。只有1个对象None,因此在执行操作时my_var is None,您要检查它们是否实际上是同一对象(而不仅仅是等效对象)

换句话说,==是检查等效性(定义在对象之间),而is检查对象身份:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

Summary:

Use is when you want to check against an object’s identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you’re checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

回答 1

is通常,在将任意对象与单例对象进行比较时,通常首选,None因为它更快且更可预测。is总是按对象身份进行比较,而==做什么取决于操作数的确切类型,甚至取决于它们的顺序。

PEP 8对此建议提供了支持,该声明明确指出 “对单例的比较(如None,应始终使用isis not,绝不能使用相等运算符进行)”。

is is generally preferred when comparing arbitrary objects to singletons like None because it is faster and more predictable. is always compares by object identity, whereas what == will do depends on the exact type of the operands and even on their ordering.

This recommendation is supported by PEP 8, which explicitly states that “comparisons to singletons like None should always be done with is or is not, never the equality operators.”


回答 2

PEP 8定义is比较单例时最好使用运算符。

PEP 8 defines that it is better to use the is operator when comparing singletons.


从列表中删除无值而不删除0值

问题:从列表中删除无值而不删除0值

这是我开始的来源。

我的清单

L = [0, 23, 234, 89, None, 0, 35, 9]

当我运行这个:

L = filter(None, L)

我得到这个结果

[23, 234, 89, 35, 9]

但这不是我所需要的,我真正需要的是:

[0, 23, 234, 89, 0, 35, 9]

因为我正在计算数据的百分位数,所以0会产生很大的不同。

如何从列表中删除无值而不删除0值?

This was my source I started with.

My List

L = [0, 23, 234, 89, None, 0, 35, 9]

When I run this :

L = filter(None, L)

I get this results

[23, 234, 89, 35, 9]

But this is not what I need, what I really need is :

[0, 23, 234, 89, 0, 35, 9]

Because I’m calculating percentile of the data and the 0 make a lot of difference.

How to remove the None value from a list without removing 0 value?


回答 0

>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]

只是为了好玩,您可以filter在不使用的情况下适应这种情况lambda(我不推荐使用此代码-只是出于科学目的)

>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> filter(partial(is_not, None), L)
[0, 23, 234, 89, 0, 35, 9]
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]

Just for fun, here’s how you can adapt filter to do this without using a lambda, (I wouldn’t recommend this code – it’s just for scientific purposes)

>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> filter(partial(is_not, None), L)
[0, 23, 234, 89, 0, 35, 9]

回答 1

FWIW,Python 3使此问题变得容易:

>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(None.__ne__, L))
[0, 23, 234, 89, 0, 35, 9]

在Python 2中,您将改为使用列表推导:

>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]

A list comprehension is likely the cleanest way:

>>> L = [0, 23, 234, 89, None, 0, 35, 9
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]

There is also a functional programming approach but it is more involved:

>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(partial(is_not, None), L))
[0, 23, 234, 89, 0, 35, 9]

回答 2

对于Python 2.7(请参阅Raymond的答案,对于Python 3等效):

想知道在Python(和其他OO语言)中是否普遍存在“不是None”的东西,以至于在我的Common.py(我使用“ from common import *”导入到每个模块)中,包括了以下几行:

def exists(it):
    return (it is not None)

然后从列表中删除None元素,只需执行以下操作:

filter(exists, L)

我发现这比相应的列表理解(Raymond以他的Python 2版本显示)更容易阅读。

For Python 2.7 (See Raymond’s answer, for Python 3 equivalent):

Wanting to know whether something “is not None” is so common in python (and other OO languages), that in my Common.py (which I import to each module with “from Common import *”), I include these lines:

def exists(it):
    return (it is not None)

Then to remove None elements from a list, simply do:

filter(exists, L)

I find this easier to read, than the corresponding list comprehension (which Raymond shows, as his Python 2 version).


回答 3

使用列表理解可以做到以下几点:

l = [i for i in my_list if i is not None]

l的值是:

[0, 23, 234, 89, 0, 35, 9]

Using list comprehension this can be done as follows:

l = [i for i in my_list if i is not None]

The value of l is:

[0, 23, 234, 89, 0, 35, 9]

回答 4

@jamylak的答案很不错,但是如果您不想导入几个模块只是为了完成这个简单的任务,请lambda就地编写自己的代码:

>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> filter(lambda v: v is not None, L)
[0, 23, 234, 89, 0, 35, 9]

@jamylak answer is quite nice, however if you don’t want to import a couple of modules just to do this simple task, write your own lambda in-place:

>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> filter(lambda v: v is not None, L)
[0, 23, 234, 89, 0, 35, 9]

回答 5

迭代空间,使用可能是一个问题。在不同情况下,分析可能会显示“更快”和/或“更少的内存”密集型。

# first
>>> L = [0, 23, 234, 89, None, 0, 35, 9, ...]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9, ...]

# second
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> for i in range(L.count(None)): L.remove(None)
[0, 23, 234, 89, 0, 35, 9, ...]

一种方法(也由@jamylak@Raymond Hettinger@Dipto提出)在内存中创建了一个重复列表,这对于只有很少None条目的大列表来说可能是昂贵的。

第二个方法经过列表一次,然后再次每次直至None到达。这可能会减少内存消耗,并且列表会变得越来越小。列表大小的减少可能会加快None前面很多条目的速度,但是最坏的情况是如果None后面很多条目。

并行化和就地技术是其他方法,但是每种方法在Python中都有其自身的复杂性。了解数据和运行时用例以及对程序进行性能分析是开始进行大量操作或处理大数据的地方。

在通常情况下,选择任何一种方法都可能无关紧要。它更多地成为符号的偏爱。实际上,在那些不常见的情况下,numpy或者cython可能是值得尝试的替代方法,而不是尝试对Python优化进行微管理。

Iteration vs Space, usage could be an issue. In different situations profiling may show either to be “faster” and/or “less memory” intensive.

# first
>>> L = [0, 23, 234, 89, None, 0, 35, 9, ...]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9, ...]

# second
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> for i in range(L.count(None)): L.remove(None)
[0, 23, 234, 89, 0, 35, 9, ...]

The first approach (as also suggested by @jamylak, @Raymond Hettinger, and @Dipto) creates a duplicate list in memory, which could be costly of memory for a large list with few None entries.

The second approach goes through the list once, and then again each time until a None is reached. This could be less memory intensive, and the list will get smaller as it goes. The decrease in list size could have a speed up for lots of None entries in the front, but the worst case would be if lots of None entries were in the back.

The second approach would likely always be slower than the first approach. That does not make it an invalid consideration.

Parallelization and in-place techniques are other approaches, but each have their own complications in Python. Knowing the data and the runtime use-cases, as well profiling the program are where to start for intensive operations or large data.

Choosing either approach will probably not matter in common situations. It becomes more of a preference of notation. In fact, in those uncommon circumstances, numpy (example if L is numpy.array: L = L[L != numpy.array(None) (from here)) or cython may be worthwhile alternatives instead of attempting to micromanage Python optimizations.


回答 6

from operator import is_not
from functools import partial   

filter_null = partial(filter, partial(is_not, None))

# A test case
L = [1, None, 2, None, 3]
L = list(filter_null(L))
from operator import is_not
from functools import partial   

filter_null = partial(filter, partial(is_not, None))

# A test case
L = [1, None, 2, None, 3]
L = list(filter_null(L))

回答 7

如果全部是列表列表,则可以修改@Raymond先生的答案

L = [ [None], [123], [None], [151] ] no_none_val = list(filter(None.__ne__, [x[0] for x in L] ) ) 对于python 2但是

no_none_val = [x[0] for x in L if x[0] is not None] """ Both returns [123, 151]"""

<<如果变量不是None,则List中变量的list_indice [0] >>

If it is all a list of lists, you could modify sir @Raymond’s answer

L = [ [None], [123], [None], [151] ] no_none_val = list(filter(None.__ne__, [x[0] for x in L] ) ) for python 2 however

no_none_val = [x[0] for x in L if x[0] is not None] """ Both returns [123, 151]"""

<< list_indice[0] for variable in List if variable is not None >>


回答 8

说列表如下

iterator = [None, 1, 2, 0, '', None, False, {}, (), []]

这只会返回那些其 bool(item) is True

print filter(lambda item: item, iterator)
# [1, 2]

这相当于

print [item for item in iterator if item]

仅过滤无:

print filter(lambda item: item is not None, iterator)
# [1, 2, 0, '', False, {}, (), []]

相当于:

print [item for item in iterator if item is not None]

要获取所有评估为False的项目

print filter(lambda item: not item, iterator)
# Will print [None, '', 0, None, False, {}, (), []]

Say the list is like below

iterator = [None, 1, 2, 0, '', None, False, {}, (), []]

This will return only those items whose bool(item) is True

print filter(lambda item: item, iterator)
# [1, 2]

This is equivalent to

print [item for item in iterator if item]

To just filter None:

print filter(lambda item: item is not None, iterator)
# [1, 2, 0, '', False, {}, (), []]

Equivalent to:

print [item for item in iterator if item is not None]

To get all the items that evaluate to False

print filter(lambda item: not item, iterator)
# Will print [None, '', 0, None, False, {}, (), []]

为什么会出现AttributeError:’NoneType’对象没有属性’something’?

问题:为什么会出现AttributeError:’NoneType’对象没有属性’something’?

我不断收到错误消息,说

AttributeError: 'NoneType' object has no attribute 'something'

我的代码太长,无法在此处发布。什么一般情况会导致这种情况AttributeError,这NoneType意味着什么,我如何缩小正在发生的事情?

I keep getting an error that says

AttributeError: 'NoneType' object has no attribute 'something'

The code I have is too long to post here. What general scenarios would cause this AttributeError, what is NoneType supposed to mean and how can I narrow down what’s going on?


回答 0

NoneType意味着您实际上拥有了而不是您认为正在使用的任何Class或Object的实例None。这通常意味着在上面的赋值或函数调用失败或返回了意外结果。

NoneType means that instead of an instance of whatever Class or Object you think you’re working with, you’ve actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result.


回答 1

您有一个等于None的变量,并且您试图访问它的名为“ something”的属性。

foo = None
foo.something = 1

要么

foo = None
print foo.something

两者都会产生一个 AttributeError: 'NoneType'

You have a variable that is equal to None and you’re attempting to access an attribute of it called ‘something’.

foo = None
foo.something = 1

or

foo = None
print(foo.something)

Both will yield an AttributeError: 'NoneType'


回答 2

其他人则解释了什么NoneType是结束它的常见方法(即,无法从函数返回值)。

另一个None不希望看到的常见原因是在可变对象上分配了就地操作。例如:

mylist = mylist.sort()

sort()列表的方法对列表进行原位排序,mylist即被修改。但是该方法的实际返回值None不是对列表进行排序。因此,您刚刚分配Nonemylist。如果您下次尝试这样做,mylist.append(1)Python会给您这个错误。

Others have explained what NoneType is and a common way of ending up with it (i.e., failure to return a value from a function).

Another common reason you have None where you don’t expect it is assignment of an in-place operation on a mutable object. For example:

mylist = mylist.sort()

The sort() method of a list sorts the list in-place, that is, mylist is modified. But the actual return value of the method is None and not the list sorted. So you’ve just assigned None to mylist. If you next try to do, say, mylist.append(1) Python will give you this error.


回答 3

NoneType是该值的类型None。在这种情况下,变量lifetime的值为None

发生这种情况的一种常见方法是调用缺少a的函数return

但是,还有无数其他方法可以将变量设置为“无”。

The NoneType is the type of the value None. In this case, the variable lifetime has a value of None.

A common way to have this happen is to call a function missing a return.

There are an infinite number of other ways to set a variable to None, however.


回答 4

考虑下面的代码。

def return_something(someint):
 if  someint > 5:
    return someint

y = return_something(2)
y.real()

这会给你错误

AttributeError:“ NoneType”对象没有属性“ real”

所以要点如下。

  1. 在代码中,函数或类方法未返回任何内容或未返回None
  2. 然后,您尝试访问该返回对象的属性(即None),从而导致错误消息。

Consider the code below.

def return_something(someint):
 if  someint > 5:
    return someint

y = return_something(2)
y.real()

This is going to give you the error

AttributeError: ‘NoneType’ object has no attribute ‘real’

So points are as below.

  1. In the code, a function or class method is not returning anything or returning the None
  2. Then you try to access an attribute of that returned object(which is None), causing the error message.

回答 5

这意味着您正在尝试访问的对象NoneNoneNullpython中的变量。这种类型的错误发生在您的代码上,就像这样。

x1 = None
print(x1.something)

#or

x1 = None
x1.someother = "Hellow world"

#or
x1 = None
x1.some_func()

# you can avoid some of these error by adding this kind of check
if(x1 is not None):
    ... Do something here
else:
    print("X1 variable is Null or None")

It means the object you are trying to access None. None is a Null variable in python. This type of error is occure de to your code is something like this.

x1 = None
print(x1.something)

#or

x1 = None
x1.someother = "Hellow world"

#or
x1 = None
x1.some_func()

# you can avoid some of these error by adding this kind of check
if(x1 is not None):
    ... Do something here
else:
    print("X1 variable is Null or None")

回答 6

gddc是正确的,但添加了一个非常常见的示例:

您可以以递归形式调用此函数。在这种情况下,您可能会以空指针或结尾NoneType。在这种情况下,您会收到此错误。因此,在访问该参数的属性之前,请检查它是否不是NoneType

g.d.d.c. is right, but adding a very frequent example:

You might call this function in a recursive form. In that case, you might end up at null pointer or NoneType. In that case, you can get this error. So before accessing an attribute of that parameter check if it’s not NoneType.


回答 7

建立估算器(sklearn)时,如果忘记在fit函数中返回self,则会得到相同的错误。

class ImputeLags(BaseEstimator, TransformerMixin):
    def __init__(self, columns):
        self.columns = columns

    def fit(self, x, y=None):
        """ do something """

    def transfrom(self, x):
        return x

AttributeError:’NoneType’对象没有属性’transform’?

添加return self到拟合功能可修复该错误。

When building a estimator (sklearn), if you forget to return self in the fit function, you get the same error.

class ImputeLags(BaseEstimator, TransformerMixin):
    def __init__(self, columns):
        self.columns = columns

    def fit(self, x, y=None):
        """ do something """

    def transfrom(self, x):
        return x

AttributeError: ‘NoneType’ object has no attribute ‘transform’?

Adding return self to the fit function fixes the error.


回答 8

在Flask应用程序中注释掉HTML时,可能会出现此错误。此处qual.date_expiry的值为None:

   <!-- <td>{{ qual.date_expiry.date() }}</td> -->

删除行或修复它:

<td>{% if qual.date_attained != None %} {{ qual.date_attained.date() }} {% endif %} </td>

You can get this error with you have commented out HTML in a Flask application. Here the value for qual.date_expiry is None:

   <!-- <td>{{ qual.date_expiry.date() }}</td> -->

Delete the line or fix it up:

<td>{% if qual.date_attained != None %} {{ qual.date_attained.date() }} {% endif %} </td>

回答 9

如果我们分配如下所示的内容,则会引发错误,例如“ AttributeError:’NoneType’对象没有属性’show’”

df1=df.withColumn('newAge',df['Age']).show() 

if we assign something like the below, it will throw error as “AttributeError: ‘NoneType’ object has no attribute ‘show'”

df1=df.withColumn('newAge',df['Age']).show() 

如果字典键不可用,则返回None

问题:如果字典键不可用,则返回None

我需要一种方法来获取字典值(如果它的键存在),或者简单地返回None,如果它不存在。

但是,KeyError如果您搜索不存在的键,Python会引发异常。我知道我可以检查密钥,但是我正在寻找更明确的密钥。None如果密钥不存在,是否有办法返回?

I need a way to get a dictionary value if its key exists, or simply return None, if it does not.

However, Python raises a KeyError exception if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not exist?


回答 0

您可以使用 dict.get()

value = d.get(key)

None如果将返回key is not in d。您还可以提供将返回的其他默认值,而不是None

value = d.get(key, "empty")

You can use dict.get()

value = d.get(key)

which will return None if key is not in d. You can also provide a different default value that will be returned instead of None:

value = d.get(key, "empty")

回答 1

别再奇怪了。它内置在语言中。

    >>>帮助(dict)

    模块内置的类字典帮助:

    类dict(object)
     | dict()->新的空字典
     | dict(mapping)->从映射对象的字典初始化的新字典
     | (键,值)对
    ...
     |  
     | 得到(...)
     | D.get(k [,d])-> D [k]如果D中有k,否则为d。d默认为无。
     |  
    ...

Wonder no more. It’s built into the language.

    >>> help(dict)

    Help on class dict in module builtins:

    class dict(object)
     |  dict() -> new empty dictionary
     |  dict(mapping) -> new dictionary initialized from a mapping object's
     |      (key, value) pairs
    ...
     |  
     |  get(...)
     |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
     |  
    ...

回答 2

采用 dict.get

如果key在字典中,则返回key的值,否则返回默认值。如果未提供default,则默认为None,因此此方法永远不会引发KeyError。

Use dict.get

Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.


回答 3

您应该使用类中的get()方法dict

d = {}
r = d.get('missing_key', None)

这将导致r == None。如果在字典中找不到键,则get函数将返回第二个参数。

You should use the get() method from the dict class

d = {}
r = d.get('missing_key', None)

This will result in r == None. If the key isn’t found in the dictionary, the get function returns the second argument.


回答 4

如果您想要一个更透明的解决方案,则可以继承dict此行为:

class NoneDict(dict):
    def __getitem__(self, key):
        return dict.get(self, key)

>>> foo = NoneDict([(1,"asdf"), (2,"qwerty")])
>>> foo[1]
'asdf'
>>> foo[2]
'qwerty'
>>> foo[3] is None
True

If you want a more transparent solution, you can subclass dict to get this behavior:

class NoneDict(dict):
    def __getitem__(self, key):
        return dict.get(self, key)

>>> foo = NoneDict([(1,"asdf"), (2,"qwerty")])
>>> foo[1]
'asdf'
>>> foo[2]
'qwerty'
>>> foo[3] is None
True

回答 5

我通常在这种情况下使用defaultdict。您提供一个不带任何参数的工厂方法,并在看到新键时创建一个值。当您想在新键上返回空列表之类的功能时,它会更有用(请参见示例)。

from collections import defaultdict
d = defaultdict(lambda: None)
print d['new_key']  # prints 'None'

I usually use a defaultdict for situations like this. You supply a factory method that takes no arguments and creates a value when it sees a new key. It’s more useful when you want to return something like an empty list on new keys (see the examples).

from collections import defaultdict
d = defaultdict(lambda: None)
print d['new_key']  # prints 'None'

回答 6

您可以使用dict对象的get()方法,就像其他人已经建议的那样。另外,根据您正在执行的操作,您可能可以使用如下try/except套件:

try:
   <to do something with d[key]>
except KeyError:
   <deal with it not being there>

这被认为是处理案件的非常“ Pythonic”的方法。

You could use a dict object’s get() method, as others have already suggested. Alternatively, depending on exactly what you’re doing, you might be able use a try/except suite like this:

try:
   <to do something with d[key]>
except KeyError:
   <deal with it not being there>

Which is considered to be a very “Pythonic” approach to handling the case.


回答 7

一线解决方案是:

item['key'] if 'key' in item else None

在尝试将字典值添加到新列表并想要提供默认值时,这很有用:

例如。

row = [item['key'] if 'key' in item else 'default_value']

A one line solution would be:

item['key'] if 'key' in item else None

This is useful when trying to add dictionary values to a new list and want to provide a default:

eg.

row = [item['key'] if 'key' in item else 'default_value']

回答 8

就像其他人说的那样,您可以使用get()。

但是要检查密钥,您也可以执行以下操作:

d = {}
if 'keyname' in d:

    # d['keyname'] exists
    pass

else:

    # d['keyname'] does not exist
    pass

As others have said above, you can use get().

But to check for a key, you can also do:

d = {}
if 'keyname' in d:

    # d['keyname'] exists
    pass

else:

    # d['keyname'] does not exist
    pass

回答 9

我被python2 vs python3中可能发生的事情吓了一跳。我将根据最终对python3所做的回答。我的目标很简单:检查字典格式的json响应是否给出错误。我的字典称为“令牌”,而我正在寻找的密钥是“错误”。我正在寻找键“错误”,如果不存在,则将其设置为“无”,然后检查其值为“无”,如果是,请继续执行我的代码。如果我确实拥有键“错误”,则将执行else语句。

if ((token.get('error', None)) is None):
    do something

I was thrown aback by what was possible in python2 vs python3. I will answer it based on what I ended up doing for python3. My objective was simple: check if a json response in dictionary format gave an error or not. My dictionary is called “token” and my key that I am looking for is “error”. I am looking for key “error” and if it was not there setting it to value of None, then checking is the value is None, if so proceed with my code. An else statement would handle if I do have the key “error”.

if ((token.get('error', None)) is None):
    do something

回答 10

如果可以使用False,则还可以使用hasattr内置功能:

e=dict()
hasattr(e, 'message'):
>>> False

If you can do it with False, then, there’s also the hasattr built-in funtion:

e=dict()
hasattr(e, 'message'):
>>> False

如何在Python中“测试” NoneType?

问题:如何在Python中“测试” NoneType?

我有一个有时返回NoneType值的方法。那么我如何质疑一个无类型的变量呢?例如,我需要使用if方法

if not new:
    new = '#'

我知道这是错误的方式,希望您能理解我的意思。

I have a method that sometimes returns a NoneType value. So how can I question a variable that is a NoneType? I need to use if method, for example

if not new:
    new = '#'

I know that is the wrong way and I hope you understand what I meant.


回答 0

那么我如何质疑一个无类型的变量呢?

is像这样使用运算符

if variable is None:

为什么这样有效?

由于NoneNoneTypePython中唯一的单例对象,因此我们可以使用isoperator来检查变量None中是否包含变量。

引用is文档

运算符isis not对象身份测试:x is y当且仅当xy是相同对象时,才为true 。x is not y产生反真值。

由于只能有一个实例Noneis因此是检查的首选方法None


从马口中听到

引用Python的编码样式指南-PEP-008(由Guido亲自定义),

与单例之类的比较None应该总是用isis not不是等式运算符进行

So how can I question a variable that is a NoneType?

Use is operator, like this

if variable is None:

Why this works?

Since None is the sole singleton object of NoneType in Python, we can use is operator to check if a variable has None in it or not.

Quoting from is docs,

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

Since there can be only one instance of None, is would be the preferred way to check None.


Hear it from the horse’s mouth

Quoting Python’s Coding Style Guidelines – PEP-008 (jointly defined by Guido himself),

Comparisons to singletons like None should always be done with is or is not, never the equality operators.


回答 1

if variable is None:
   ...

if variable is not None:
   ...
if variable is None:
   ...

if variable is not None:
   ...

回答 2

也可以isinstance按照Alex Hall的回答来完成:

>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True

isinstance 也很直观,但有一个复杂之处,那就是需要

NoneType = type(None)

对于像int和这样的类型,则不需要float

It can also be done with isinstance as per Alex Hall’s answer :

>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True

isinstance is also intuitive but there is the complication that it requires the line

NoneType = type(None)

which isn’t needed for types like int and float.


回答 3

正如亚伦·霍尔的评论所指出的:

由于您不能继承子类,NoneType并且由于None是单例,isinstance因此不应将其用于检测None-而是应按照已接受的答案进行操作,并使用is Noneis not None


原始答案:

但是,最简单的方法,除了豆蔻果实的答案外,没有多余内容可能是:
isinstance(x, type(None))

那么我如何质疑一个无类型的变量呢?我需要使用if方法

使用isinstance()不需要is的内if语句来:

if isinstance(x, type(None)): 
    #do stuff

其他信息
您还可以isinstance()按照文档中的说明在一个语句中检查多种类型。只需将类型写为元组即可。

isinstance(x, (type(None), bytes))

As pointed out by Aaron Hall’s comment:

Since you can’t subclass NoneType and since None is a singleton, isinstance should not be used to detect None – instead you should do as the accepted answer says, and use is None or is not None.


Original Answer:

The simplest way however, without the extra line in addition to cardamom’s answer is probably:
isinstance(x, type(None))

So how can I question a variable that is a NoneType? I need to use if method

Using isinstance() does not require an is within the if-statement:

if isinstance(x, type(None)): 
    #do stuff

Additional information
You can also check for multiple types in one isinstance() statement as mentioned in the documentation. Just write the types as a tuple.

isinstance(x, (type(None), bytes))

回答 4

不知道这是否能回答问题。但是我知道这花了我一段时间才能弄清楚。我浏览了一个网站,突然间,作者的名字不再存在。因此需要一个检查语句。

if type(author) == type(None):
     my if body
else:
    my else body

在这种情况下,作者可以是任何变量,也None可以是您要检查的任何类型。

Not sure if this answers the question. But I know this took me a while to figure out. I was looping through a website and all of sudden the name of the authors weren’t there anymore. So needed a check statement.

if type(author) == type(None):
     my if body
else:
    my else body

Author can be any variable in this case, and None can be any type that you are checking for.


回答 5

Python 2.7:

x = None
isinstance(x, type(None))

要么

isinstance(None, type(None))

==>正确

Python 2.7 :

x = None
isinstance(x, type(None))

or

isinstance(None, type(None))

==> True


回答 6

希望这个例子对您有帮助)

print(type(None) # NoneType

因此,您可以检查变量名称的类型

#Example
name = 12 # name = None
if type(name) != type(None):
    print(name)
else:
    print("Can't find name")

I hope this example will be helpful for you)

print(type(None) # NoneType

So, you can check type of the variable name

#Example
name = 12 # name = None
if type(name) != type(None):
    print(name)
else:
    print("Can't find name")