Skip to content

Fix using() to not mutate closure-captured kwargs dict#3044

Merged
birkenfeld merged 1 commit intopygments:masterfrom
bysiber:fix/using-kwargs-mutation
Feb 20, 2026
Merged

Fix using() to not mutate closure-captured kwargs dict#3044
birkenfeld merged 1 commit intopygments:masterfrom
bysiber:fix/using-kwargs-mutation

Conversation

@bysiber
Copy link
Copy Markdown
Contributor

@bysiber bysiber commented Feb 20, 2026

Problem

using() callbacks mutate the closure-captured kwargs dict via kwargs.update(lexer.options). This causes two issues:

  1. State accumulation: The dict grows with each invocation, mixing in options from previous lexer instances.

  2. Wrong precedence: kwargs.update(lexer.options) gives the parent lexer's generic options priority over the explicitly-provided kwargs. For example, using(PhpLexer, startinline=True) can be overridden if the parent lexer was created with startinline=False.

Fix

Create a fresh dict per callback invocation. Start from lexer.options and then overlay explicit kwargs, so user-specified arguments take priority:

d = dict(lexer.options)
d.update(kwargs)
lx = _other(**d)

using() callbacks called kwargs.update(lexer.options), permanently
mutating the dict captured from the class definition.  This caused
two problems:

1. Accumulated state across calls — the dict grew with each
   invocation, mixing in options from previous instances.

2. Wrong precedence — lexer.options (parent) overwrote kwargs
   (explicit), so e.g. using(PhpLexer, startinline=True) could
   be overridden by the parent lexer's startinline=False.

Use a fresh copy per call, with explicit kwargs taking priority
over inherited options.
@birkenfeld
Copy link
Copy Markdown
Member

Makes sense to me, thanks.

@birkenfeld birkenfeld merged commit cecaaf8 into pygments:master Feb 20, 2026
28 of 30 checks passed
@Anteru Anteru added this to the 2.20.0 milestone Mar 26, 2026
@Anteru Anteru added the A-api area: changes to Pygments API or cmdline label Mar 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-api area: changes to Pygments API or cmdline

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants