3

With isinstance we can check whether something is of a certain type, but how can we test whether an object is a class belonging to a certain module?

Example:

>>> type(root)
<class 'bs4.BeautifulSoup'>

>>> isinstance(root, BeautifulSoup)
True

How to test whether this object "belongs" to the bs4 package?

Note: When I go over the objects in the soup recursively, it starts as a bs4.BeautifulSoup object, but at another level they are bs4.element.Tag nodes. This is why I want to check for originating from this module rather than a particular type.

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160

1 Answers1

3

If I understand you correctly, you want to know the module of an object. Is that correct? If so, you will want to check the object's __module__ attribute:

>>> from bs4 import BeautifulSoup
>>> BeautifulSoup.__module__     # module of BeautifulSoup
'bs4'

>>> import requests
>>> r = requests.get('http://www.google.com')
>>> soup = BeautifulSoup(r.content)
>>> soup.__module__               # module of a BeautifulSoup object
'bs4'

In light of your comment, you may be after something like this:

>>> soup = BeautifulSoup('<b class="boldest">A bold statement.</b>')
>>> tag = soup.b
>>> tag.__module__                # module of a Tag object
'bs4.element'
Justin O Barber
  • 11,291
  • 2
  • 40
  • 45