Skip to content

Instantly share code, notes, and snippets.

@israel-dryer
Created February 25, 2021 05:05
Show Gist options
  • Save israel-dryer/31483417318e6a07093094c31733f5b5 to your computer and use it in GitHub Desktop.
Save israel-dryer/31483417318e6a07093094c31733f5b5 to your computer and use it in GitHub Desktop.
Instantiate all the classes in a target module without explicitly naming them
import sys
from datetime import datetime
class GoogleNewsScraper():
def __init__(self):
self.date_modified = datetime.today()
def scrape(self):
print(f"scraping data from google news: {self.date_modified: %Y-%m-%d}.")
class YahooNewsScraper():
def __init__(self):
self.date_modified = datetime.today()
def scrape(self):
print(f"scraping data from yahoo news: {self.date_modified: %Y-%m-%d}.")
if __name__ == '__main__':
# get target module --> replace with actual module name if referencing external module
target_module = sys.modules[__name__]
module_contents = dir(target_module)
# get all relevant classes in the module
class_list = []
for c in module_contents:
if not c in ('sys', 'datetime', 'target_module') and not c.startswith('__'):
class_list.append(getattr(target_module, c))
# instantiate all classes and call the scrape method
scrapers = [s() for s in class_list]
for s in scrapers:
s.scrape()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment