Skip to content

[Python]Fix type inference for closures in lambdas - #36080

Closed
Suvrat1629 wants to merge 1 commit into
apache:masterfrom
Suvrat1629:closure_type
Closed

[Python]Fix type inference for closures in lambdas#36080
Suvrat1629 wants to merge 1 commit into
apache:masterfrom
Suvrat1629:closure_type

Conversation

@Suvrat1629

Copy link
Copy Markdown
Contributor

Please add a meaningful description for your change here


Fixes #28420
Fixes type inference bug in load_closure where captured variables in inner lambdas (closures) were incorrectly inferred as type instead of their actual type (e.g., int).Updates load_closure in apache_beam/typehints/opcodes.py to use inferred types from the inference state context, with fallback to typehints.Any.

Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@github-actions github-actions Bot added the python label Sep 7, 2025

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @Suvrat1629, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical type inference bug within Apache Beam's Python SDK, specifically concerning how types are determined for variables captured by closures in lambda functions. The change ensures that the type hinting system accurately identifies and propagates the correct types for these variables, improving the reliability of type analysis within the framework.

Highlights

  • Closure Type Inference: Resolves a bug in load_closure where captured variables within inner lambdas (closures) were not correctly inferring their specific types, leading to incorrect type assignments.
  • Enhanced Type Resolution: Updates the load_closure function to prioritize inferred types from the inference state context, ensuring more precise type propagation, with typehints.Any as a robust fallback.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@github-actions

github-actions Bot commented Sep 7, 2025

Copy link
Copy Markdown
Contributor

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers

@stankiewicz

Copy link
Copy Markdown
Contributor

please review logs:

TrivialInferenceTest.testDictComprehension __________________
[gw1] linux -- Python 3.10.17 /runner/_work/beam/beam/sdks/python/test-suites/tox/py310/build/srcs/sdks/python/target/.tox-py310/py310/bin/python

self = <apache_beam.typehints.trivial_inference_test.TrivialInferenceTest testMethod=testDictComprehension>

    def testDictComprehension(self):
      fields = []
      expected_type = typehints.Dict[typehints.Any, typehints.Any]
>     self.assertReturnType(
          expected_type, lambda row: {f: row[f] for f in fields}, [typehints.Any])

apache_beam/typehints/trivial_inference_test.py:357: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
apache_beam/typehints/trivial_inference_test.py:38: in assertReturnType
    trivial_inference.infer_return_type(f, inputs, debug=True, depth=depth))
target/.tox-py310/py310/lib/python3.10/site-packages/apache_beam/yaml/yaml_provider.py:554: in infer_return_type
    return original_infer_return_type(fn, *args, **kwargs)
target/.tox-py310/py310/lib/python3.10/site-packages/apache_beam/typehints/trivial_inference.py:297: in infer_return_type
    return infer_return_type_func(c, input_types, debug, depth)
target/.tox-py310/py310/lib/python3.10/site-packages/apache_beam/typehints/trivial_inference.py:626: in infer_return_type_func
    simple_ops[opname](state, arg)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

state = Stack: [Any] Vars: [Any], arg = 0

    def load_closure(state, arg):
      # The arg is no longer offset by len(covar_names) as of 3.11
      # See https://docs.python.org/3/library/dis.html#opcode-LOAD_CLOSURE
      if (sys.version_info.major, sys.version_info.minor) >= (3, 11):
        arg -= len(state.co.co_varnames)
      state.stack.append(state.closure_type(arg))
      closure_idx = arg
>     inferred_type = state.closure_type[closure_idx] if hasattr(state, 'closure_types') else state.get_inferred_type_for_closure(closure_idx)
E     AttributeError: 'FrameState' object has no attribute 'get_inferred_type_for_closure'

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been marked as stale due to 60 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the dev@beam.apache.org list. Thank you for your contributions.

@github-actions github-actions Bot added the stale label Nov 24, 2025
@github-actions

github-actions Bot commented Dec 1, 2025

Copy link
Copy Markdown
Contributor

This pull request has been closed due to lack of activity. If you think that is incorrect, or the pull request requires review, you can revive the PR at any time.

@github-actions github-actions Bot closed this Dec 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Type inference failure with closure creation.

2 participants