Skip to content

Fix prefix slicing on numbers and quoting in reserved expansion - #165

Open
Fire162 wants to merge 1 commit into
python-hyper:mainfrom
Fire162:fix-prefix-and-reserved-expansion
Open

Fire162 wants to merge 1 commit into
python-hyper:mainfrom
Fire162:fix-prefix-and-reserved-expansion

Conversation

@Fire162

@Fire162 Fire162 commented Oct 24, 2026

Copy link
Copy Markdown

Closes #163

Prefix modifiers caused a TypeError when values were integers or floats because value[:prefix] expected subscriptable objects. Converting the value to string first before slicing allows prefix modifiers to work on numeric values.

In reserved expansions, _only_quote_unquoted_characters skipped quoting entirely if the string already contained any percent-encoded characters, leaving characters like spaces unencoded. Splitting on valid percent-encoded triplets allows preserving existing escapes while encoding remaining unescaped characters.

Convert values to string before applying prefix slicing so numeric and non-string values can be sliced with prefix modifiers without raising TypeError.

In reserved expansion, split on existing percent-encoded triplets so unescaped characters are quoted without double-encoding existing percent escapes.
Comment thread uritemplate/variable.py

value = t.cast(t.Text, value)
value = value[:prefix] if prefix else value
value = str(value)[:prefix] if prefix else value

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

str(value) also changes bytes values, which quote() still accepts and decodes (isinstance(value, bytes) in Operator.quote). With a prefix, the slice now runs on the repr:

from uritemplate import expand
expand("{x:2}", x=b"abc")   # main: 'ab'     this PR: 'b%27'
expand("{?x:2}", x=b"abc")  # main: '?x=ab'  this PR: '?x=b%27'

Same for the /, ; and plain branches (all four str(value)[:prefix] lines). Without a prefix it is fine, since value is left as is.

A fix that keeps the number case working: only call str() on non-text values, for example

if not isinstance(value, (str, bytes)):
    value = str(value)
value = value[:prefix] if prefix else value

(or decode bytes first, so the prefix counts characters, not bytes). A test like expand("{x:2}", x=b"abc") == "ab" would cover it.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Prefix modifier crashes on non-string values; reserved expansion stops encoding once the value contains a percent-escape

2 participants