Python 中的空对象

发布于 2024-09-11 02:37:52 字数 104 浏览 1 评论 0原文

如何在 Python 中引用 null 对象

How do I refer to the null object in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

浅笑依然 2024-09-18 02:37:52

在 Python 中,“null”对象是单例 None

要检查某些内容是否为 None,请使用 身份运算符:

if foo is None:
    ...

In Python, the 'null' object is the singleton None.

To check if something is None, use the is identity operator:

if foo is None:
    ...
小耗子 2024-09-18 02:37:52

None,Python 的 null?

Python 中没有 null;相反,有。如前所述,测试某项是否已被赋予 None 作为值的最准确方法是使用 is 恒等运算符,该运算符测试两个变量是否引用相同的变量目的。

>>> foo is None
True
>>> foo = 'bar'
>>> foo is None
False

基础知识

存在且只能有一个 None

None 是类 NoneType 的唯一实例,任何进一步尝试实例化该类都将返回同一个对象,这使得 None 成为单例。 Python 新手经常会看到提到 NoneType 的错误消息,并且想知道它是什么。我个人认为,这些消息可以简单地提及 None 的名称,因为我们很快就会看到,None 几乎没有留下任何歧义的空间。因此,如果您看到一些 TypeError 消息提到 NoneType 不能执行此操作或不能执行该操作,只需知道它只是一个 None 正在以一种它不能的方式使用。

此外,None 是一个内置常量。一旦您启动 Python,就可以在任何地方使用它,无论是在模块、类还是函数中。相比之下,NoneType 则不然,您需要首先通过查询 None 的类来获取对它的引用。

>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType

您可以使用 Python 的身份函数 id() 检查 None 的唯一性。它返回分配给对象的唯一编号,每个对象都有一个。如果两个变量的id相同,那么它们实际上指向同一个对象。

>>> NoneType = type(None)
>>> id(None)
10748000
>>> my_none = NoneType()
>>> id(my_none)
10748000
>>> another_none = NoneType()
>>> id(another_none)
10748000
>>> def function_that_does_nothing(): pass
>>> return_value = function_that_does_nothing()
>>> id(return_value)
10748000

None 无法被覆盖

在更旧的 Python 版本(2.4 之前)中,可以重新分配 None,但现在不能了。即使作为类属性或在函数范围内也不行。

# In Python 2.7
>>> class SomeClass(object):
...     def my_fnc(self):
...             self.None = 'foo'
SyntaxError: cannot assign to None
>>> def my_fnc():
        None = 'foo'
SyntaxError: cannot assign to None

# In Python 3.5
>>> class SomeClass:
...     def my_fnc(self):
...             self.None = 'foo'
SyntaxError: invalid syntax
>>> def my_fnc():
        None = 'foo'
SyntaxError: cannot assign to keyword

因此,可以安全地假设所有 None 引用都是相同的。没有任何“自定义”None

要测试 None,请使用 is 运算符

在编写代码时,您可能会想像这样测试 Noneness

if value==None:
    pass

或者像这样测试 false

if not value:
    pass

您需要了解其中的含义以及为什么明确表达通常是一个好主意。

案例 1:测试某个值是否为 None

为什么要这样做

value is None

而不是

value==None

第一个相当于:

id(value)==id(None)

而表达式 value==None 实际上是这样应用的

value.__eq__(None)

如果值确实是 None 那么您将得到您所期望的结果。

>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True

在大多数常见情况下,结果是相同的,但 __eq__() 方法打开了一扇无法保证准确性的大门,因为它可以在类中被重写以提供特殊行为。

考虑一下这个类。

>>> class Empty(object):
...     def __eq__(self, other):
...         return not other

因此,您在 None 上尝试,它可以工作

>>> empty = Empty()
>>> empty==None
True

但是它也可以在空字符串上工作

>>> empty==''
True

但是

>>> ''==None
False
>>> empty is None
False

案例 2:使用 None 作为布尔值

以下两个测试

if value:
    # Do something

if not value:
    # Do something

实际上评估了 因为

if bool(value):
    # Do something

if not bool(value):
    # Do something

None 是一个“falsey”,这意味着如果转换为布尔值,它将返回 False,如果应用 not 运算符,它将返回 <代码>真。但请注意,它不是 None 独有的属性。除了 False 本身之外,该属性还由空列表、元组、集合、字典、字符串以及 0 以及实现 __bool__() 的类中的所有对象共享。 code> 返回 False 的魔术方法。

>>> bool(None)
False
>>> not None
True

>>> bool([])
False
>>> not []
True

>>> class MyFalsey(object):
...     def __bool__(self):
...         return False
>>> f = MyFalsey()
>>> bool(f)
False
>>> not f
True

因此,当按以下方式测试变量时,请额外注意您在测试中包含或排除的内容:

def some_function(value=None):
    if not value:
        value = init_value()

在上面,您是否打算在专门设置值时调用 init_value()None,或者您的意思是设置为 0 的值、空字符串或空列表也应该触发初始化?就像我说的,要留心。通常情况下,在 Python 中显式优于隐式。

None 实践中

None 用作信号值

None 在 Python 中具有特殊地位。它是最受欢迎的基线值,因为许多算法将其视为特殊值。在这种情况下,它可以用作标志来表明某个条件需要一些特殊处理(例如设置默认值)。

您可以将 None 分配给函数的关键字参数,然后显式测试它。

def my_function(value, param=None):
    if param is None:
        # Do something outrageous!

当尝试获取对象的属性时,您可以将其作为默认值返回,然后在执行特殊操作之前显式测试它。

value = getattr(some_obj, 'some_attribute', None)
if value is None:
    # do something spectacular!

默认情况下,字典的 get() 方法在尝试访问不存在的键时返回 None

>>> some_dict = {}
>>> value = some_dict.get('foo')
>>> value is None
True

如果您尝试使用下标表示法来访问它,则会返回 则会引发>KeyError

>>> value = some_dict['foo']
KeyError: 'foo'

同样,如果您尝试弹出一个不存在的项目

>>> value = some_dict.pop('foo')
KeyError: 'foo'

的默认值来抑制该项目,

value = some_dict.pop('foo', None)
if value is None:
    # Booom!

,您可以使用通常设置为 None None 作为标志和有效值

上述使用 None 的情况适用于它不被视为有效值的情况,但更像是执行某些特殊操作的信号。然而,在某些情况下,了解 None 来自何处有时很重要,因为即使它被用作信号,它也可能是数据的一部分。

当您使用 getattr(some_obj, 'attribute_name', None) 查询对象的属性时,返回 None 不会告诉您您尝试访问的属性是否是设置为 None 或者如果它完全不存在于对象中。从字典中访问键时的情况相同,例如 some_dict.get('some_key'),您不知道 some_dict['some_key'] 是否丢失或如果它只是设置为None。如果您需要该信息,处理此问题的常用方法是直接尝试从 try/ except 构造中访问属性或键:

try:
    # Equivalent to getattr() without specifying a default
    # value = getattr(some_obj, 'some_attribute')
    value = some_obj.some_attribute
    # Now you handle `None` the data here
    if value is None:
        # Do something here because the attribute was set to None
except AttributeError:
    # We're now handling the exceptional situation from here.
    # We could assign None as a default value if required.
    value = None
    # In addition, since we now know that some_obj doesn't have the
    # attribute 'some_attribute' we could do something about that.
    log_something(some_obj)

与 dict 类似:

try:
    value = some_dict['some_key']
    if value is None:
        # Do something here because 'some_key' is set to None
except KeyError:
    # Set a default
    value = None
    # And do something because 'some_key' was missing
    # from the dict.
    log_something(some_dict)

上面的两个示例显示了如何处理 object 和字典案例。功能呢?同样的事情,但我们使用双星号关键字参数来达到此目的:

def my_function(**kwargs):
    try:
        value = kwargs['some_key']
        if value is None:
            # Do something because 'some_key' is explicitly
            # set to None
    except KeyError:
        # We assign the default
        value = None
        # And since it's not coming from the caller.
        log_something('did not receive "some_key"')

None仅用作有效值

如果您发现您的代码中充斥着上述try/ except 模式只是为了区分 None 标志和 None 数据,然后只需使用另一个测试值。有一种模式,其中超出有效值集的值作为数据的一部分插入数据结构中,并用于控制和测试特殊条件(例如边界、状态等)。这样的值称为哨兵,它可以像None用作信号一样使用。在 Python 中创建哨兵很简单。

undefined = object()

上面的 undefined 对象是唯一的,并且不会做任何程序可能感兴趣的事情,因此它是 None 作为标志的绝佳替代品。需要注意一些注意事项,更多关于代码后面的内容。

使用函数

def my_function(value, param1=undefined, param2=undefined):
    if param1 is undefined:
        # We know nothing was passed to it, not even None
        log_something('param1 was missing')
        param1 = None


    if param2 is undefined:
        # We got nothing here either
        log_something('param2 was missing')
        param2 = None

使用 dict

value = some_dict.get('some_key', undefined)
if value is None:
    log_something("'some_key' was set to None")

if value is undefined:
    # We know that the dict didn't have 'some_key'
    log_something("'some_key' was not set at all")
    value = None

使用对象

value = getattr(obj, 'some_attribute', undefined)
if value is None:
    log_something("'obj.some_attribute' was set to None")
if value is undefined:
    # We know that there's no obj.some_attribute
    log_something("no 'some_attribute' set on obj")
    value = None

正如我之前提到的,自定义哨兵有一些注意事项。首先,它们不是像 None 这样的关键字,因此 Python 不保护它们。您可以随时在定义的模块中的任何位置覆盖上面的 undefined,因此要小心如何公开和使用它们。接下来,object() 返回的实例不是单例。如果您调用 10 次,您将获得 10 个不同的对象。最后,哨兵的使用非常特殊。哨兵是特定于它所使用的库的,因此它的范围通常应限于库的内部。它不应该“泄漏”出去。只有当外部代码的目的是扩展或补充库的 API 时,它们才应该意识到这一点。

None, Python's null?

There's no null in Python; instead there's None. As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.

>>> foo is None
True
>>> foo = 'bar'
>>> foo is None
False

The basics

There is and can only be one None

None is the sole instance of the class NoneType and any further attempts at instantiating that class will return the same object, which makes None a singleton. Newcomers to Python often see error messages that mention NoneType and wonder what it is. It's my personal opinion that these messages could simply just mention None by name because, as we'll see shortly, None leaves little room to ambiguity. So if you see some TypeError message that mentions that NoneType can't do this or can't do that, just know that it's simply the one None that was being used in a way that it can't.

Also, None is a built-in constant. As soon as you start Python, it's available to use from everywhere, whether in module, class, or function. NoneType by contrast is not, you'd need to get a reference to it first by querying None for its class.

>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType

You can check None's uniqueness with Python's identity function id(). It returns the unique number assigned to an object, each object has one. If the id of two variables is the same, then they point in fact to the same object.

>>> NoneType = type(None)
>>> id(None)
10748000
>>> my_none = NoneType()
>>> id(my_none)
10748000
>>> another_none = NoneType()
>>> id(another_none)
10748000
>>> def function_that_does_nothing(): pass
>>> return_value = function_that_does_nothing()
>>> id(return_value)
10748000

None cannot be overwritten

In much older versions of Python (before 2.4) it was possible to reassign None, but not any more. Not even as a class attribute or in the confines of a function.

# In Python 2.7
>>> class SomeClass(object):
...     def my_fnc(self):
...             self.None = 'foo'
SyntaxError: cannot assign to None
>>> def my_fnc():
        None = 'foo'
SyntaxError: cannot assign to None

# In Python 3.5
>>> class SomeClass:
...     def my_fnc(self):
...             self.None = 'foo'
SyntaxError: invalid syntax
>>> def my_fnc():
        None = 'foo'
SyntaxError: cannot assign to keyword

It's therefore safe to assume that all None references are the same. There isn't any "custom" None.

To test for None use the is operator

When writing code you might be tempted to test for Noneness like this:

if value==None:
    pass

Or to test for falsehood like this

if not value:
    pass

You need to understand the implications and why it's often a good idea to be explicit.

Case 1: testing if a value is None

Why do

value is None

rather than

value==None

?

The first is equivalent to:

id(value)==id(None)

Whereas the expression value==None is in fact applied like this

value.__eq__(None)

If the value really is None then you'll get what you expected.

>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True

In most common cases the outcome will be the same, but the __eq__() method opens a door that voids any guarantee of accuracy, since it can be overridden in a class to provide special behavior.

Consider this class.

>>> class Empty(object):
...     def __eq__(self, other):
...         return not other

So you try it on None and it works

>>> empty = Empty()
>>> empty==None
True

But then it also works on the empty string

>>> empty==''
True

And yet

>>> ''==None
False
>>> empty is None
False

Case 2: Using None as a boolean

The following two tests

if value:
    # Do something

if not value:
    # Do something

are in fact evaluated as

if bool(value):
    # Do something

if not bool(value):
    # Do something

None is a "falsey", meaning that if cast to a boolean it will return False and if applied the not operator it will return True. Note however that it's not a property unique to None. In addition to False itself, the property is shared by empty lists, tuples, sets, dicts, strings, as well as 0, and all objects from classes that implement the __bool__() magic method to return False.

>>> bool(None)
False
>>> not None
True

>>> bool([])
False
>>> not []
True

>>> class MyFalsey(object):
...     def __bool__(self):
...         return False
>>> f = MyFalsey()
>>> bool(f)
False
>>> not f
True

So when testing for variables in the following way, be extra aware of what you're including or excluding from the test:

def some_function(value=None):
    if not value:
        value = init_value()

In the above, did you mean to call init_value() when the value is set specifically to None, or did you mean that a value set to 0, or the empty string, or an empty list should also trigger the initialization? Like I said, be mindful. As it's often the case, in Python explicit is better than implicit.

None in practice

None used as a signal value

None has a special status in Python. It's a favorite baseline value because many algorithms treat it as an exceptional value. In such scenarios it can be used as a flag to signal that a condition requires some special handling (such as the setting of a default value).

You can assign None to the keyword arguments of a function and then explicitly test for it.

def my_function(value, param=None):
    if param is None:
        # Do something outrageous!

You can return it as the default when trying to get to an object's attribute and then explicitly test for it before doing something special.

value = getattr(some_obj, 'some_attribute', None)
if value is None:
    # do something spectacular!

By default a dictionary's get() method returns None when trying to access a non-existing key:

>>> some_dict = {}
>>> value = some_dict.get('foo')
>>> value is None
True

If you were to try to access it by using the subscript notation a KeyError would be raised

>>> value = some_dict['foo']
KeyError: 'foo'

Likewise if you attempt to pop a non-existing item

>>> value = some_dict.pop('foo')
KeyError: 'foo'

which you can suppress with a default value that is usually set to None

value = some_dict.pop('foo', None)
if value is None:
    # Booom!

None used as both a flag and valid value

The above described uses of None apply when it is not considered a valid value, but more like a signal to do something special. There are situations however where it sometimes matters to know where None came from because even though it's used as a signal it could also be part of the data.

When you query an object for its attribute with getattr(some_obj, 'attribute_name', None) getting back None doesn't tell you if the attribute you were trying to access was set to None or if it was altogether absent from the object. The same situation when accessing a key from a dictionary, like some_dict.get('some_key'), you don't know if some_dict['some_key'] is missing or if it's just set to None. If you need that information, the usual way to handle this is to directly attempt accessing the attribute or key from within a try/except construct:

try:
    # Equivalent to getattr() without specifying a default
    # value = getattr(some_obj, 'some_attribute')
    value = some_obj.some_attribute
    # Now you handle `None` the data here
    if value is None:
        # Do something here because the attribute was set to None
except AttributeError:
    # We're now handling the exceptional situation from here.
    # We could assign None as a default value if required.
    value = None
    # In addition, since we now know that some_obj doesn't have the
    # attribute 'some_attribute' we could do something about that.
    log_something(some_obj)

Similarly with dict:

try:
    value = some_dict['some_key']
    if value is None:
        # Do something here because 'some_key' is set to None
except KeyError:
    # Set a default
    value = None
    # And do something because 'some_key' was missing
    # from the dict.
    log_something(some_dict)

The above two examples show how to handle object and dictionary cases. What about functions? The same thing, but we use the double asterisks keyword argument to that end:

def my_function(**kwargs):
    try:
        value = kwargs['some_key']
        if value is None:
            # Do something because 'some_key' is explicitly
            # set to None
    except KeyError:
        # We assign the default
        value = None
        # And since it's not coming from the caller.
        log_something('did not receive "some_key"')

None used only as a valid value

If you find that your code is littered with the above try/except pattern simply to differentiate between None flags and None data, then just use another test value. There's a pattern where a value that falls outside the set of valid values is inserted as part of the data in a data structure and is used to control and test special conditions (e.g. boundaries, state, etc.). Such a value is called a sentinel and it can be used the way None is used as a signal. It's trivial to create a sentinel in Python.

undefined = object()

The undefined object above is unique and doesn't do much of anything that might be of interest to a program, it's thus an excellent replacement for None as a flag. Some caveats apply, more about that after the code.

With function

def my_function(value, param1=undefined, param2=undefined):
    if param1 is undefined:
        # We know nothing was passed to it, not even None
        log_something('param1 was missing')
        param1 = None


    if param2 is undefined:
        # We got nothing here either
        log_something('param2 was missing')
        param2 = None

With dict

value = some_dict.get('some_key', undefined)
if value is None:
    log_something("'some_key' was set to None")

if value is undefined:
    # We know that the dict didn't have 'some_key'
    log_something("'some_key' was not set at all")
    value = None

With an object

value = getattr(obj, 'some_attribute', undefined)
if value is None:
    log_something("'obj.some_attribute' was set to None")
if value is undefined:
    # We know that there's no obj.some_attribute
    log_something("no 'some_attribute' set on obj")
    value = None

As I mentioned earlier, custom sentinels come with some caveats. First, they're not keywords like None, so Python doesn't protect them. You can overwrite your undefined above at any time, anywhere in the module it's defined, so be careful how you expose and use them. Next, the instance returned by object() is not a singleton. If you make that call 10 times you get 10 different objects. Finally, usage of a sentinel is highly idiosyncratic. A sentinel is specific to the library it's used in and as such its scope should generally be limited to the library's internals. It shouldn't "leak" out. External code should only become aware of it, if their purpose is to extend or supplement the library's API.

风吹过旳痕迹 2024-09-18 02:37:52

它不像其他语言那样被称为 null,而是 None。该对象始终只有一个实例,因此如果需要,您可以使用 x is None (身份比较)而不是 x == None 检查等效性。

It's not called null as in other languages, but None. There is always only one instance of this object, so you can check for equivalence with x is None (identity comparison) instead of x == None, if you want.

潦草背影 2024-09-18 02:37:52

在 Python 中,要表示不存在值,可以对对象使用 None 值 (types.NoneType.None),并使用 "" (或 len() == 0)对于字符串。因此:

if yourObject is None:  # if yourObject == None:
    ...

if yourString == "":  # if yourString.len() == 0:
    ...

关于“==”和“is”之间的区别,使用“==”测试对象身份应该足够了。然而,由于操作“is”被定义为对象标识操作,因此使用它可能比“==”更正确。不确定是否存在速度差异。

无论如何,你可以看看:

In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:

if yourObject is None:  # if yourObject == None:
    ...

if yourString == "":  # if yourString.len() == 0:
    ...

Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.

Anyway, you can have a look at:

冬天的雪花 2024-09-18 02:37:52

上面的答案只会在 None 的情况下得出 True,但有 float('nan') 之类的东西。你可以使用pandas isnull

>>> import pandas as pd
>>> pd.isnull(None)
True
>>> pd.isnull(float('nan'))
True
>>> pd.isnull('abc')
False
>>> 

或者不使用pandas

>>> a = float('nan')
>>> (a != a) or (a == None)
True
>>> a = None
>>> (a != a) or (a == None)
True
>>> 

它起作用的原因是float('nan') != float('nan')

>>> float('nan') == float('nan')
False
>>> float('nan') != float('nan')
True
>>> 

The above answers only will result True for None, but there is such a thing as float('nan'). You could use pandas isnull:

>>> import pandas as pd
>>> pd.isnull(None)
True
>>> pd.isnull(float('nan'))
True
>>> pd.isnull('abc')
False
>>> 

Or without pandas:

>>> a = float('nan')
>>> (a != a) or (a == None)
True
>>> a = None
>>> (a != a) or (a == None)
True
>>> 

The reason this works is because float('nan') != float('nan'):

>>> float('nan') == float('nan')
False
>>> float('nan') != float('nan')
True
>>> 
何止钟意 2024-09-18 02:37:52

使用 f 字符串来解决这个问题。

year=None
year_val= 'null' if year is None else  str(year)
print(f'{year_val}')

null

Use f string for getting this solved.

year=None
year_val= 'null' if year is None else  str(year)
print(f'{year_val}')

null
音栖息无 2024-09-18 02:37:52

Python 中处理“空”元素的简单函数:

代码:

def is_empty(element) -> bool:
    """
    Function to check if input `element` is empty.

    Other than some special exclusions and inclusions,
    this function returns boolean result of Falsy check.
    """
    if (isinstance(element, int) or isinstance(element, float)) and element == 0:
        # Exclude 0 and 0.0 from the Falsy set.
        return False
    elif isinstance(element, str) and len(element.strip()) == 0:
        # Include string with one or more empty space(s) into Falsy set.
        return True
    elif isinstance(element, bool):
        # Exclude False from the Falsy set.
        return False
    else:
        # Falsy check.
        return False if element else True

测试:

print("Is empty?\n")
print('"" -> ', is_empty(""))
print('"      " -> ', is_empty("      "))
print('"A" -> ', is_empty("A"))
print('"a" -> ', is_empty("a"))
print('"0" -> ', is_empty("0"))
print("0 -> ", is_empty(0))
print("0.0 -> ", is_empty(0.0))
print("[] -> ", is_empty([]))
print("{} -> ", is_empty({}))
print("() -> ", is_empty(()))
print("[1, 2] -> ", is_empty([1, 2]))
print("(3, 5) -> ", is_empty((3, 5)))
print('{"a": 1} -> ', is_empty({"a": 1}))
print("None -> ", is_empty(None))
print("True -> ", is_empty(True))
print("False -> ", is_empty(False))
print("NaN -> ", is_empty(float("nan")))
print("range(0) -> ", is_empty(range(0)))

输出:

Is empty?

"" ->  True
"      " ->  True
"A" ->  False
"a" ->  False
"0" ->  False
0 ->  False
0.0 ->  False
[] ->  True
{} ->  True
() ->  True
[1, 2] ->  False
(3, 5) ->  False
{"a": 1} ->  False
None ->  True
True ->  False
False ->  False
NaN ->  False
range(0) ->  True

Simple function to tackle "empty" element in Python:

Code:

def is_empty(element) -> bool:
    """
    Function to check if input `element` is empty.

    Other than some special exclusions and inclusions,
    this function returns boolean result of Falsy check.
    """
    if (isinstance(element, int) or isinstance(element, float)) and element == 0:
        # Exclude 0 and 0.0 from the Falsy set.
        return False
    elif isinstance(element, str) and len(element.strip()) == 0:
        # Include string with one or more empty space(s) into Falsy set.
        return True
    elif isinstance(element, bool):
        # Exclude False from the Falsy set.
        return False
    else:
        # Falsy check.
        return False if element else True

Test:

print("Is empty?\n")
print('"" -> ', is_empty(""))
print('"      " -> ', is_empty("      "))
print('"A" -> ', is_empty("A"))
print('"a" -> ', is_empty("a"))
print('"0" -> ', is_empty("0"))
print("0 -> ", is_empty(0))
print("0.0 -> ", is_empty(0.0))
print("[] -> ", is_empty([]))
print("{} -> ", is_empty({}))
print("() -> ", is_empty(()))
print("[1, 2] -> ", is_empty([1, 2]))
print("(3, 5) -> ", is_empty((3, 5)))
print('{"a": 1} -> ', is_empty({"a": 1}))
print("None -> ", is_empty(None))
print("True -> ", is_empty(True))
print("False -> ", is_empty(False))
print("NaN -> ", is_empty(float("nan")))
print("range(0) -> ", is_empty(range(0)))

Output:

Is empty?

"" ->  True
"      " ->  True
"A" ->  False
"a" ->  False
"0" ->  False
0 ->  False
0.0 ->  False
[] ->  True
{} ->  True
() ->  True
[1, 2] ->  False
(3, 5) ->  False
{"a": 1} ->  False
None ->  True
True ->  False
False ->  False
NaN ->  False
range(0) ->  True
谁的年少不轻狂 2024-09-18 02:37:52

想象一下,如果查询为变量测试返回空值

test if test !=None else 0

Imagine if the query is returning null value for variable test

test if test !=None else 0
梦行七里 2024-09-18 02:37:52

根据 真值测试,“None”直接测试为 FALSE,因此最简单的表达式就足够了:

if not foo:

Per Truth value testing, 'None' directly tests as FALSE, so the simplest expression will suffice:

if not foo:
北恋 2024-09-18 02:37:52

Null 是一种特殊的对象类型,例如:

>>>type(None)
<class 'NoneType'>

您可以检查对象是否在“NoneType”类中:

>>>variable = None
>>>variable is None
True

更多信息可在 Python 文档

Null is a special object type like:

>>>type(None)
<class 'NoneType'>

You can check if an object is in class 'NoneType':

>>>variable = None
>>>variable is None
True

More information is available at Python Docs

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文