Generating error if callable object is formatted as a string?

Open
#5,213 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
python
Domain
devtools

Research direction

Start by reviewing the three examples and the four proposed options in the issue. The issue names no files, tests, or entry points; completion would require choosing and specifying a behavior for callable objects passed to formatting or str(), including how valid cases are silenced.

Written by the indexing model from the issue text.

Description

needs discussion

Pretty frequently I have errors where I forget to call a method and accidentally pass a method object to % or str.format. Mypy doesn't complain since it's possible to convert a callable object to a string, though usually that's not what I want.

Example:

class Item:
    def name(self) -> str: ...

def f(x: Item) -> None:
    print('name: {}'.format(x.name))  # No error, though should be x.name() 
    print('name: %s' % x.name)  # Similar to above
    foo(str(x.name))  # Ditto

This occasionally happens during refactoring as well, when I replace an instance variable with a method.

Here are a few things we could do about this:

  1. Special case these errors and generate a warning even though the code is not necessarily wrong. Maybe require an explicit repr(x.some_method) to silence the error (# type: ignore or a cast to object would also work).
  2. Introduce a new strictness flag that causes these to be flagged. Not sure if this should be enabled by default.
  3. Introduce a new strictness flag that catches these and other cases where there is no runtime type error, but that we suspect might be errors. Passing a string argument when an iterable object is expected comes to mind as a kind of similar issue, and there are probably others.
  4. Do nothing, since there is no runtime type error and the code could well be valid.

Option 2 seems too specialized -- this doesn't seem important enough to add a strictness flag. Personally I prefer the more opinionated option 1. We could add a hint about how to silence the error in case the code happens to be correct.

Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.