Skip to content

Fix Locale subclass __str__ issue - #1271

Open
Chiifouu wants to merge 1 commit into
python-babel:masterfrom
Chiifouu:master
Open

Fix Locale subclass __str__ issue#1271
Chiifouu wants to merge 1 commit into
python-babel:masterfrom
Chiifouu:master

Conversation

@Chiifouu

@Chiifouu Chiifouu commented May 9, 2026

Copy link
Copy Markdown

Fixes #1252

I noticed that Locale.init was using str(self) to build the identifier. This breaks when a subclass overrides str with a custom format.

This PR replaces it with get_locale_identifier() and adds a small test to make sure subclassed Locale objects work correctly.

@akx akx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Instead of duplicating the get_locale_identifier invocation from __str__, maybe we should add a new @property called _identifier and use it in both places?

@nathaniel-kotzrenko-hs

Copy link
Copy Markdown

@akx imo that would change the standard usage of the existing get_locale_identifier function.
In this case it makes more sense to modify all call sites (there are several in this class) to use the @property but won't it just mean another layer of indirection?

I think @Chiifouu's solution is good for this case, it doesn't modify the existing standard but does decouple __str__ behavior from affecting the class, clean and straightforward, no need to modify the existing standard.

@akx

akx commented Jul 31, 2026

Copy link
Copy Markdown
Member

@nathaniel-kotzrenko-hs

imo that would change the standard usage of the existing get_locale_identifier function.

I don't see how - you'd use get_locale_identifier() to build an identifier from raw parts as before.

In this case it makes more sense to modify all call sites (there are several in this class)

As far as I can see, there's only one call site that uses the Locale instance's values, and that's __str__. Other call sites (Locale.parse, default_locale()) don't.

but won't it just mean another layer of indirection?

In my eyes, it'll be the one canonical way to get the instance's full locale identifier, even if __str__ is overridden.

To be clear, I mean Locale.__str__() should just return self._identifier, and places where str(locale) are being currently used should use locale._identifier. (I'm slightly hesitant about making it identifier, i.e. a public API.)

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.

Locale class uses str(...) in __init__

3 participants