facebook / facebook/pyrefly

Django: Instance vs Class access of attributes should return different types

Open
#4,080 0 comments 2 reactions 1 assignee Claimed by @asukaminato0721 View on GitHub
django pydantic typechecking
Dominant language
Rust
Stars
7k
Forks
516
PR merge metrics
No merged PRs in 30d

Description

### Describe the Bug

Take an example model

```python
class Contact(models.Model):
address = models.CharField(max_length=200)
```

When accessing the type from an instance we get the correct str return

```python
item = Contact(address="123 Fake St")
reveal_type(item.address) # revealed_type: str
```

But when accessing the class attribute we gain access to the FieldDescriptor which lets access metadata about the field.

For example:

```python
class ContactUpdatePayload(pydantic.BaseModel):
new_address: Annotated[
str,
pydantic.Field(max_length=Contact.address.field.max_length), # error: Object of class `str` has no attribute `field` Did you mean `find`?
]

reveal_type(Contact.address) # revealed_type: str
# expected: django.db.models.fields._FieldDescriptor[django.db.models.fields.CharField[str | int | django.db.models.expressions.Combinable, str]]

reveal_type(Contact.address.field.max_length) # revealed_type: Unknown
# expected: int | None
```

Ideally the type should be different when accessing the field via the instance vs the class

### Sandbox Link

_No response_

### (Only applicable for extension issues) IDE Information

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.