replace_with and unwrap fail to check the parent is None

Bug #1463984 reported by Zhaogui
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
Beautiful Soup
Fix Released
Undecided
Unassigned

Bug Description

It gives an attributeerror traceback when self.parent is None, which confuses me.

[simple test]

builder = builder.TreeBuilder()
parent_tag = Tag(name='div', attrs={'id': 'parent'}, builder=builder)
replace_tag = Tag(name='div', attrs={'id': 'replace'}, builder=builder)

parent_tag.replace_with(replace_tag)

Traceback
...
    parent_tag.replace_with(replace_tag)
  File "/usr/lib/python2.7/dist-packages/bs4/element.py", line 211, in replace_with
    my_index = self.parent.index(self)
AttributeError: 'NoneType' object has no attribute 'index'

It is similar in method "unwarp".

Zhaogui (xzhg71107214)
description: updated
Revision history for this message
Leonard Richardson (leonardr) wrote :

The exception message is bad, but raising an exception is the correct behavior. unwrap() and replace_with() don't alter an element in place: they change the way that element shows up in a tree. If the element has no .parent it's not part of a tree, and .unwrap() and .replace_with() don't mean anything.

Here's an analogy. If you have a list [1, 2, 3] you can replace the 2 with a 5 to get [1, 5, 3]. But if you just have the number 2, you can't replace it with a 5. It's not in a context where 'replacement' makes sense.

I think you probably want to do something different, but I'm not sure what.

I've improved the exception messages to hopefully make it more clear why the exception is happening.

Changed in beautifulsoup:
status: New → Fix Committed
Changed in beautifulsoup:
status: Fix Committed → Fix Released
To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.