Value Of Py_none
Solution 1:
Py_None
is a macro definition in Include/object.h
. It is a an alias for _Py_NoneStruct
in object.c
which is a static (as in storage) global variable of PyObject
type (which is a struct). It is assigned in Python terms to be of NoneType
(defined right above it in object.c
and only used once for _Py_NoneStruct
).
So it's not NULL or any other special value in C, it's a singleton PyObject
instance of _PyNone_Type
. As for the _PyNone_Type
PyTypeObject
not being exposed, I suppose they refer to the static
keyword (i.e. internal linkage) which means that the PyTypeObject
is only accessible within object.c
and is only used once for the definition of PyNone
.
Just to add to this a bit, whenever the documentation says that PyNone
has no type, it should not be taken literally. It has a special kind of type, NoneType
, which you can still access through the None
singleton but you can't create new instances or do any other thing you can do with a normal type. There seems to be a hard-coded limitation for not creating new instances, and although I can't find exactly where it's defined in the CPython source you can see its effect when trying to create a new instance:
>>> type(None)
<type'NoneType'>
>>> type(None)()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create 'NoneType' instances
EDIT: It seems that the error is thrown from typeobject.c
when the tp_new
field is NULL. Surprisingly though _PyNone_Type
seems to be defined with a non-NULL tp_new
(points to the static none_new
in object.c
). It might be set to NULL afterwards at some point, but it's just an implementation detail and doesn't really make a difference for the scope of your question.
Solution 2:
Py_None
is Py_None
, and must be increfed and returned from a function during normal operation if no other value is to be returned. NULL
is only returned if an exception is to be signaled to the VM, with the actual exception object created/assigned separately.
Solution 3:
Py_None
is the value of the address of the _Py_NoneStruct
struct definition.
See the code:
/*
_Py_NoneStruct is an object of undefined type which can be used in contexts
where NULL (nil) is not suitable (since NULL often means 'error').
Don't forget to apply Py_INCREF() when returning this value!!!
*/PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */#define Py_None (&_Py_NoneStruct)
Post a Comment for "Value Of Py_none"