Skip to content

Bug: 'with' fails when context variable from outer scope #37

@swernerx

Description

@swernerx

Description

Python's with context manager statement is not being converted and remains as invalid TypeScript syntax.

Python Input

with open(file, 'rb') as f:
    data = f.read()

with ctx as handle:
    process(handle)

with nullcontext() as nc:
    do_something()

Current Output (v1.3.3)

with open(file, 'rb') as f:  // ❌ INVALID! 'with' is different in JS
    let data = f.read();

with ctx as handle:  // ❌ INVALID!
    process(handle);

Expected Output

const f = open(file, 'rb')
try {
  const data = f.read()
} finally {
  f[Symbol.dispose]?.() ?? f.close?.()
}

// Or simpler without dispose:
const handle = ctx
try {
  process(handle)
} finally {
  handle.close?.()
}

Note

Earlier versions of python2ts correctly converted with statements to try/finally blocks (I saw this in simple test cases). This might be a regression or only happens in specific contexts.

Affected Files

Found ~60 occurrences in NumPy migration.

Priority

🔴 Critical - Causes ~200 errors

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions