Skip to content

repr(TzInfo(0)) returns invalid python code #1691

Closed
@15r10nk

Description

@15r10nk

Hi, I'm the author of inline-snapshot and have a problem with the way TzInfo.__repr__ is implemented.

TzInfo has currently the following repr:

from pydantic_core import TzInfo

def test_TzInfo():
    assert repr(TzInfo(0)) == 'TzInfo(UTC)'
    assert repr(TzInfo(1)) == 'TzInfo(+00:00:01)'
    assert repr(TzInfo(5000)) == 'TzInfo(+01:23:20)'

The problem is that inline-snapshot uses by default repr() to generate the python code for the snapshots.

from pydantic_core import TzInfo
import datetime
from inline_snapshot import snapshot


def test_TzInfo():
    assert datetime.datetime(1, 2, 3, tzinfo=TzInfo(0)) == snapshot(
        datetime.datetime(1, 2, 3, 0, 0, tzinfo=TzInfo(UTC))
    )

inline-snapshot users then try to import UTC from somewhere which causes other problems.

Is it possible to change the repr() result of TzInfo to the following (add "").

from pydantic_core import TzInfo

def test_TzInfo():
    assert repr(TzInfo(0)) == 'TzInfo("UTC")'
    assert repr(TzInfo(1)) == 'TzInfo("+00:00:01")'
    assert repr(TzInfo(5000)) == 'TzInfo("+01:23:20")'

And to provide the possibility for TzInfo to be constructed from a string?

This should make

assert eval(repr(tzinfo)) == tzinfo

work for all TzInfo objects.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions