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

Fix false positive error when calling an UnboundMethodValue #548

Merged
merged 3 commits into from
Nov 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- Fix false positive error certain method calls on literals (#548)
- Preserve `Annotated` annotations on access to methods of
literals (#541)
- `allow_call` callables are now also called if the arguments
Expand Down
12 changes: 12 additions & 0 deletions pyanalyze/test_attributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,3 +351,15 @@ def capybara(x: Union[A, B]):
if hasattr(x, "a") and hasattr(x, "b"):
assert_is_value(x.a, AnyValue(AnySource.inference))
assert_is_value(x.b, AnyValue(AnySource.inference))

@assert_passes()
def test_hasattr_plus_call(self):
class X:
@classmethod
def types(cls):
return []

def capybara(x: X) -> None:
cls = X
if hasattr(cls, "types"): # E: value_always_true
assert_is_value(cls.types(), AnyValue(AnySource.unannotated))
14 changes: 8 additions & 6 deletions pyanalyze/value.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ def function(x: int, y: list[int], z: Any):

import collections.abc
import enum
import inspect
import textwrap
from collections import deque, OrderedDict
from dataclasses import dataclass, field, InitVar
Expand Down Expand Up @@ -544,17 +543,20 @@ class UnboundMethodValue(Value):
def get_method(self) -> Optional[Any]:
"""Return the runtime callable for this ``UnboundMethodValue``, or
None if it cannot be found."""
root = self.composite.value
if isinstance(root, AnnotatedValue):
root = root.value
if isinstance(root, KnownValue):
typ = root.val
else:
typ = root.get_type()
try:
typ = self.composite.value.get_type()
method = getattr(typ, self.attr_name)
if self.secondary_attr_name is not None:
method = getattr(method, self.secondary_attr_name)
# don't use unbound methods in py2
if inspect.ismethod(method) and method.__self__ is None:
method = method.__func__
return method
except AttributeError:
return None
return method

def is_type(self, typ: type) -> bool:
return isinstance(self.get_method(), typ)
Expand Down