Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[attribute-error] when usage is protected by an if statement #1867

Open
cjw296 opened this issue Feb 11, 2025 · 2 comments
Open

[attribute-error] when usage is protected by an if statement #1867

cjw296 opened this issue Feb 11, 2025 · 2 comments

Comments

@cjw296
Copy link

cjw296 commented Feb 11, 2025

I have this class method:

    @classmethod
    def _adjust_instance_using_tzinfo(cls, instance: datetime) -> datetime:
        if cls._mock_tzinfo:
            offset = cls._mock_tzinfo.utcoffset(instance)
            if offset is None:
                raise TypeError('tzinfo with .utcoffset() returning None is not supported')
            instance = instance - offset
        return instance

...where pytype complains but mypy does not, and it feels like the pytype complaint is erroneous:

[10/35] check testfixtures.datetime
FAILED: /Users/chris/vcs/git/testfixtures/.pytype/pyi/testfixtures/datetime.pyi 
/Users/chris/virtualenvs/testfixtures_312/bin/python -m pytype.main --disable import-error --imports_info /Users/chris/vcs/git/testfixtures/.pytype/imports/testfixtures.datetime.imports --module-name testfixtures.datetime --platform darwin -V 3.12 -o /Users/chris/vcs/git/testfixtures/.pytype/pyi/testfixtures/datetime.pyi --analyze-annotated --nofail --quick /Users/chris/vcs/git/testfixtures/testfixtures/datetime.py
/Users/chris/vcs/git/testfixtures/testfixtures/datetime.py:264:22: error: in _adjust_instance_using_tzinfo: No attribute 'utcoffset' on None [attribute-error]
  In Optional[datetime.tzinfo]

            offset = cls._mock_tzinfo.utcoffset(instance)
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~

Even if I change the guarding if block to be if cls._mock_tzinfo is not None, the complaint remains.

@martindemello
Copy link
Contributor

pytype doesn't assume an attribute access returns the same object when called twice in succession. the workaround is to assign it to a local variable first, i.e. x = cls.mock_tzinfo; if x: ...

@cjw296
Copy link
Author

cjw296 commented Feb 12, 2025

@martindemello - hmm, that seems quite an unfortunate choice, do you know if there are plans to change that?
(the fact you refer to it as a workaround gives me a little hope...)

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

No branches or pull requests

2 participants