Categories
Python Answers

How to get object by id() with Python?

Sometimes, we want to get object by id() with Python.

In this article, we’ll look at how to get object by id() with Python.

How to get object by id() with Python?

To get object by id() with Python, w ecan use the ctypes module.

For instance, we write

import ctypes

a = "hello world"
print(ctypes.cast(id(a), ctypes.py_object).value)

to get the object a‘s ID with id(a).

Then we get the object by the ID with

ctypes.cast(id(a), ctypes.py_object)

Finally, we get the object’s value with value.

Conclusion

To get object by id() with Python, w ecan use the ctypes module.

Categories
Python Answers

How to find all the subclasses of a class given its name with Python?

Sometimes, we want to find all the subclasses of a class given its name with Python.

In this article, we’ll look at how to find all the subclasses of a class given its name with Python.

How to find all the subclasses of a class given its name with Python?

To find all the subclasses of a class given its name with Python, we can use the __subclasses__ property.

For instance, we write

class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass

print([cls.__name__ for cls in Foo.__subclasses__()])

to create 4 classes.

Then we get all the subclasses of Foo with Foo.__subclasses__().

And then we get the name of each class with the __name__ property.

Conclusion

To find all the subclasses of a class given its name with Python, we can use the __subclasses__ property.

Categories
Python Answers

How to creating a dictionary from a csv file with Python?

Sometimes, we want to creating a dictionary from a csv file with Python.

In this article, we’ll look at how to creating a dictionary from a csv file with Python.

How to creating a dictionary from a csv file with Python?

To creating a dictionary from a csv file with Python, we can use dictionary comprehension.

For instance, we write

import csv

with open("coors.csv", mode="r") as infile:
    reader = csv.reader(infile)
    mydict = {rows[0]: rows[1] for rows in reader}

to open the coors.csv file with open.

Then we call csv.reader to read the file.

And then we create the mydict dict with the first entry of each row as the keys and the 2nd entry of each row as the value.

Conclusion

To creating a dictionary from a csv file with Python, we can use dictionary comprehension.

Categories
Python Answers

How to remove duplicate dict in list in Python?

Sometimes, we want to remove duplicate dict in list in Python.

In this article, we’ll look at how to remove duplicate dict in list in Python.

How to remove duplicate dict in list in Python?

To remove duplicate dict in list in Python, we use the iteration-utilities package.

To install it, we run

pip install iteration-utilities

Then we write

from iteration_utilities import unique_everseen

l = [{'a': 123}, {'b': 123}, {'a': 123}]
no_dups = list(unique_everseen(l))

to call unique_everseen to return an iterator with the duplicate dicts removed.

And then we convert that to a list with list.

Conclusion

To remove duplicate dict in list in Python, we use the iteration-utilities package.

Categories
Python Answers

How to grab visible webpage text with Python BeautifulSoup?

Sometimes, we want to grab visible webpage text with Python BeautifulSoup.

In this article, we’ll look at how to grab visible webpage text with Python BeautifulSoup.

How to grab visible webpage text with Python BeautifulSoup?

To grab visible webpage text with Python BeautifulSoup, we can call findAll with the text argument set to True.

For instance, we write

from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request


def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    if isinstance(element, Comment):
        return False
    return True


def text_from_html(body):
    soup = BeautifulSoup(body, 'html.parser')
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)  
    return u" ".join(t.strip() for t in visible_texts)

html = urllib.request.urlopen('http://www.example.com').read()
print(text_from_html(html))

to call urlopen to make GET request to a URL.

Then we call text_from_html to parse the html returned.

In text_from_html, we create a BeautifulSoup object.

And then we call findAll on the BeautifulSoup object with text set to True to get the visible text.

Next, we call filter with tag_visible to return the items that has the tags for visible elements.

And then we call join on the returned iterator to return the visible text as a string.

Conclusion

To grab visible webpage text with Python BeautifulSoup, we can call findAll with the text argument set to True.