Skip to content
This repository was archived by the owner on Sep 3, 2026. It is now read-only.
This repository was archived by the owner on Sep 3, 2026. It is now read-only.

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

Closed

Description

@cjw296

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.

Activity

  1. martindemello commented on Feb 11, 2025

    @martindemello
    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: ...

  2. cjw296 commented on Feb 12, 2025

    @cjw296
    Author

    @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...)

  3. h-joo commented on Aug 20, 2025

    @h-joo
    Contributor

    Hi, thank you for your report. Google is shifting its effort to a different approach for type checking apart from pytype, and we're not planning to put in any effort in the near future in pytype, so we'll close this issue. Please see the announcement here.

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

Metadata

Metadata

Assignees

No one assigned

    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