Lxml type 'None' is not None

I want to compare a variable I set to None

what used to be a string element with is

, but it fails.

When I compare this variable with None

with ==

, it works.

This is the variable I'm talking about:

print type(xml.a) -> <type 'lxml.objectify.StringElement'>

      

Since some of the libraries I use have None

a default (i.e. def f(x=None)

) argument , I used to convert null strings like this:

if xml.a == '':
    xml.a = None

      

After that, the type changed to:

print type(xml.a) -> <type 'lxml.objectify.NoneElement'>

      

This is not the same as:

print type(None) -> <type 'NoneType'>

      

When I compare this value as described above, I get the following result:

if xml.a is None:
    print 'what I expect'
else:
    print 'what I do NOT expect'  # sadly this one is printed

if xml.a == None:
    print 'what I do NOT expect'  # this one is printed again...
else:
    print 'what I expect'

      

I already know that when comparing objects that are not the same instance, is

returns false

. But my understanding is that I installed xml.a

in an instance earlier None

. On the other hand, they do not correspond to their types, but is

returns false

, so it cannot be the same instance as None

.

  • Why?
  • I have no choice but to use ==

    ?

For those looking to learn more about the difference between is

and isinstance

, it has been discussed here.

+3


source to share


1 answer


You are using the lxml.objectify

API
; this API uses a special object to represent values None

in an objectified XML tree. When you have assigned None

- xml.a

, lxml

, save this special object, so that he could convert it to an XML-element in an XML document.

You have no singleton None

. Instead, you have an instance of lxml.objectify.NoneElement

class
.



You can check this element type instead:

from lxml.objectify import NoneElement

if isinstance(xml.a, NoneElement):

      

+9


source







All Articles