Refactoring OOP methods with exec()

22 hours ago 4
ARTICLE AD BOX

I have OOP with the following methods:

import bs4 class Parser(): def __init__(self, html): self.html = html self.soup = bs4.BeautifulSoup(html, "html.parser") def __get_socials(self): socials = self.soup.select("div.external-links") assert 1 == len(socials) return socials[0] def __get_social(self, aria_label): social_tags = self.__get_socials() social_results = social_tags.select(f"a[aria-label='{aria_label}']") if 0 == len(social_results): return assert 1 == len(social_results) return social_results[0].get("href") def get_website(self): return self.__get_social("website") def get_instagram(self): return self.__get_social("instagram") def get_facebook(self): return self.__get_social("facebook")

I'm learning LISP macros at the same time, so just for fun (not for readability), I would like to refactor the last three as:

for stub in ["website", "instagram", "facebook"]: exec(f'{" " * 8}def get_{stub}(self):\n{" " * 12}return self.__get_social("{stub}")')

But I get SyntaxError (which is the same if I use 4-8 spaces, or 0-4 spaces)

File "test.py", line 41, in <module> class Parser(parser.Parser): File "test.py", line 142, in Parser eval(f'{" " * 4}def get_{stub}(self):\n{" " * 8}return self.__get_social("{stub}")') File "<string>", line 1 def get_website(self): ^^^ SyntaxError: invalid syntax

I also tried:

self.get_instagram = lambda self: return self.__get_social("instagram")

and I get this error:

File "test.py", line 144 self.get_instagram = lambda self: return self.__get_social("instagram") ^^^^^^ SyntaxError: invalid syntax

Is it possible in Python to refactor object methods with exec() ?

Read Entire Article