Last active
August 20, 2019 09:16
-
-
Save ethaizone/7316a0d261b00560e55cdafb505e3efb to your computer and use it in GitHub Desktop.
Python recursive call as decorator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from bson import ObjectId | |
import functools | |
# Created by Nimit Suwannagate | |
def recursive_all(f): | |
""" | |
Decorator for making recursive function. | |
:param f: | |
:return: | |
""" | |
@functools.wraps(f) | |
def wrapper(*args): | |
# Check if variable is list, make recursive call | |
if isinstance(args[0], list): | |
for index, child_v in enumerate(args[0]): | |
args[0][index] = wrapper(child_v) | |
# Check if variable is dict, make recursive call too. | |
if isinstance(args[0], dict): | |
for key, child_v in args[0].items(): | |
args[0].__setitem__(key, wrapper(child_v)) | |
return f(args[0]) | |
return wrapper | |
@recursive_all | |
def convert_safe_jsonify(v: any) -> any: | |
""" | |
Convert variable to safe type for jsonify | |
:param v: | |
:return: | |
""" | |
# Add type conversion for safe jsonify | |
# jsonify don't support object id so make it as string | |
if isinstance(v, ObjectId): | |
v = str(v) | |
return v | |
# OLD WAY! | |
def old__convert_safe_jsonify(v: any) -> any: | |
""" | |
Convert variable to safe type for jsonify | |
:param v: | |
:return: | |
""" | |
# Check if variable is list, make recursive call | |
if isinstance(v, list): | |
for index, child_v in enumerate(v): | |
v[index] = convert_safe_jsonify(child_v) | |
# Check if variable is dict, make recursive call too. | |
if isinstance(v, dict): | |
for key, child_v in v.items(): | |
v.__setitem__(key, convert_safe_jsonify(child_v)) | |
# Add type conversion for safe jsonify | |
# jsonify don't support object id so make it as string | |
if isinstance(v, ObjectId): | |
v = str(v) | |
return v | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment