make get_default_cfg a classmethod
Summary: Pull Request resolved: https://github.com/facebookresearch/d2go/pull/293 In order to pass runner during the workflow using "runner name" instead of runner instance, we need to make sure the `get_default_cfg` is not instance method. It can be either staticmethod or classmethod, but I choose classmethod for better inheritance. code mode using following script: ``` #!/usr/bin/env python3 import json import os import subprocess result = subprocess.check_output("fbgs --json 'def get_default_cfg('", shell=True) fbgs = json.loads(result) fbsource_root = os.path.expanduser("~") def _indent(s): return len(s) - len(s.lstrip()) def resolve_instance_method(content): lines = content.split("\n") for idx, line in enumerate(lines): if "def get_default_cfg(self" in line: indent = _indent(line) # find the class for j in range(idx, 0, -1): if lines[j].startswith(" " * (indent - 4) + "class "): class_line = lines[j] break else: raise RuntimeError("Can't find class") print("class_line: ", class_line) if "Runner" in class_line: # check self if not used for j in range(idx + 1, len(lines)): if _indent(lines[j]) < indent: break assert "self" not in lines[j], (j, lines[j]) # update the content assert "def get_default_cfg(self)" in line lines[idx] = lines[idx].replace( "def get_default_cfg(self)", "def get_default_cfg(cls)" ) lines.insert(idx, " " * indent + "classmethod") return "\n".join(lines) return content def resolve_static_method(content): lines = content.split("\n") for idx, line in enumerate(lines): if "def get_default_cfg()" in line: indent = _indent(line) # find the class for j in range(idx, 0, -1): if "class " in lines[j]: class_line = lines[j] break else: print("[WARNING] Can't find class!!!") continue if "Runner" in class_line: # check staticmethod is used for j in range(idx, 0, -1): if lines[j] == " " * indent + "staticmethod": staticmethod_line_idx = j break else: raise RuntimeError("Can't find staticmethod") # update the content lines[idx] = lines[idx].replace( "def get_default_cfg()", "def get_default_cfg(cls)" ) lines[staticmethod_line_idx] = " " * indent + "classmethod" return "\n".join(lines) return content for result in fbgs["results"]: filename = os.path.join(fbsource_root, result["file_name"]) print(f"processing: {filename}") with open(filename) as f: content = f.read() orig_content = content while True: old_content = content content = resolve_instance_method(content) content = resolve_static_method(content) if content == old_content: break if content != orig_content: print("Updating ...") with open(filename, "w") as f: f.write(content) ``` Reviewed By: tglik Differential Revision: D37059264 fbshipit-source-id: b09d5518f4232de95d8313621468905cf10a731c
Showing
Please register or sign in to comment