MCPcopy
hub / github.com/python/mypy / get_init

Method get_init

mypy/stubgen.py:1290–1324  ·  view source on GitHub ↗

Return initializer for a variable. Return None if we've generated one already or if the variable is internal.

(
        self, lvalue: str, rvalue: Expression, annotation: Type | None = None
    )

Source from the content-addressed store, hash-verified

1288 self.record_name(target_name)
1289
1290 def get_init(
1291 self, lvalue: str, rvalue: Expression, annotation: Type | None = None
1292 ) -> str | None:
1293 """Return initializer for a variable.
1294
1295 Return None if we've generated one already or if the variable is internal.
1296 """
1297 if lvalue in self._vars[-1]:
1298 # We've generated an initializer already for this variable.
1299 return None
1300 # TODO: Only do this at module top level.
1301 if self.is_private_name(lvalue) or self.is_not_in_all(lvalue):
1302 return None
1303 self._vars[-1].append(lvalue)
1304 if annotation is not None:
1305 typename = self.print_annotation(annotation)
1306 if (
1307 isinstance(annotation, UnboundType)
1308 and not annotation.args
1309 and annotation.name == "Final"
1310 and self.import_tracker.module_for.get("Final") in self.TYPING_MODULE_NAMES
1311 ):
1312 # Final without type argument is invalid in stubs.
1313 final_arg = self.get_str_type_of_node(rvalue)
1314 typename += f"[{final_arg}]"
1315 elif self.processing_enum:
1316 initializer, _ = self.get_str_default_of_node(rvalue)
1317 return f"{self._indent}{lvalue} = {initializer}\n"
1318 elif self.processing_dataclass:
1319 # attribute without annotation is not a dataclass field, don't add annotation.
1320 return f"{self._indent}{lvalue} = ...\n"
1321 else:
1322 typename = self.get_str_type_of_node(rvalue)
1323 initializer = self.get_assign_initializer(rvalue)
1324 return f"{self._indent}{lvalue}: {typename}{initializer}\n"
1325
1326 def get_assign_initializer(self, rvalue: Expression) -> str:
1327 """Does this rvalue need some special initializer value?"""

Callers 2

visit_func_defMethod · 0.95
visit_assignment_stmtMethod · 0.95

Calls 9

get_str_type_of_nodeMethod · 0.95
isinstanceFunction · 0.85
is_private_nameMethod · 0.80
is_not_in_allMethod · 0.80
appendMethod · 0.80
print_annotationMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected