mwchase icon

Internal annotation analysis function

mwchase | PRO | 06/06/18 05:49:16 PM UTC | 0 ⭐ | 831 👁️ | Never ⏰ | []
Python |

990 B

|

None

|

0 👍

/

0 👎

def _args_length(constructor, global_ns):
    if isinstance(constructor, str):
        ctor_ast = ast.parse(constructor, mode='eval')
        if (
                isinstance(ctor_ast.body, ast.Subscript)
                and isinstance(ctor_ast.body.slice, ast.Index)):
            index = ctor_ast.body.slice.value
            ctor_ast.body = ctor_ast.body.value
            try:
                value = eval(
                    compile(ctor_ast, '<annotation>', 'eval'),
                    global_ns,
                    global_ns)
            except Exception:
                return None
            if value is Ctor:
                if isinstance(index, ast.Tuple):
                    return len(index.elts)
                return 1
        try:
            constructor = eval(constructor, global_ns, global_ns)
        except Exception:
            return None
    if issubclass(constructor, Ctor) and constructor is not Ctor:
        return len(constructor.__args__)
    return None

Comments