MCPcopy Index your code
hub / github.com/python/mypy / _add_init

Function _add_init

mypy/plugins/attrs.py:873–907  ·  view source on GitHub ↗

Generate an __init__ method for the attributes and add it to the class.

(
    ctx: mypy.plugin.ClassDefContext,
    attributes: list[Attribute],
    adder: MethodAdder,
    method_name: Literal["__init__", "__attrs_init__"],
)

Source from the content-addressed store, hash-verified

871
872
873def _add_init(
874 ctx: mypy.plugin.ClassDefContext,
875 attributes: list[Attribute],
876 adder: MethodAdder,
877 method_name: Literal["__init__", "__attrs_init__"],
878) -> None:
879 """Generate an __init__ method for the attributes and add it to the class."""
880 # Convert attributes to arguments with kw_only arguments at the end of
881 # the argument list
882 pos_args = []
883 kw_only_args = []
884 sym_table = ctx.cls.info.names
885 for attribute in attributes:
886 if not attribute.init:
887 continue
888 if attribute.kw_only:
889 kw_only_args.append(attribute.argument(ctx))
890 else:
891 pos_args.append(attribute.argument(ctx))
892
893 # If the attribute is Final, present in `__init__` and has
894 # no default, make sure it doesn't error later.
895 if not attribute.has_default and attribute.name in sym_table:
896 sym_node = sym_table[attribute.name].node
897 if isinstance(sym_node, Var) and sym_node.is_final:
898 sym_node.final_set_in_init = True
899 args = pos_args + kw_only_args
900 if all(arg.variable.type and is_unannotated_any(arg.variable.type) for arg in args):
901 # This workaround makes --disallow-incomplete-defs usable with attrs,
902 # but is definitely suboptimal as a long-term solution.
903 # See https://github.com/python/mypy/issues/5954 for discussion.
904 for a in args:
905 a.variable.type = AnyType(TypeOfAny.implementation_artifact)
906 a.type_annotation = AnyType(TypeOfAny.implementation_artifact)
907 adder.add_method(method_name, args, NoneType())
908
909
910def _add_attrs_magic_attribute(

Callers 1

Calls 8

is_unannotated_anyFunction · 0.90
AnyTypeClass · 0.90
NoneTypeClass · 0.90
isinstanceFunction · 0.85
allFunction · 0.85
appendMethod · 0.80
argumentMethod · 0.80
add_methodMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…