Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm complains about patch.object but why?

Pretty basic setup:

import mock
from mock import patch

def test_foo():
  with patch.object(MyObject...):
    # do some stuff here...

PyCharm warning: Cannot find reference 'object' in 'function'.

If to pop up mock.py, patch.object is defined as:

patch.object = _patch_object

So how to make the warning to go away?

like image 563
Schultz9999 Avatar asked Apr 21 '15 20:04

Schultz9999


1 Answers

There are 2 ways to get rid of the warning that I've found.

Option 1. You can make the warning go away by putting "# noinspection PyUnresolvedReferences" above the patch call:

import mock
from mock import patch

def test_foo():

    # noinspection PyUnresolvedReferences
    with patch.object(MyObject...):
        # do some stuff here...

This quiets the inspector for the call and makes the warning go away. PyCharm still doesn't know anything about it, but the warning has gone away.

I believe that Mikko Ohtamaa is correct. PyCharm doesn't understand that you can add things to function objects after definition. It sees "patch" and looks at the definition and doesn't find an "object" property, hence the warning.

Option 2. The other way that I've found to get rid of the warning is to just define it in your file. Assign it to itself. Oddly, this works for me and all patch warnings go away. Your mileage may vary depending on what other inspections you have enabled.

import mock
from mock import patch
patch.object = patch.object

def test_foo():

    with patch.object(MyObject...):
        # do some stuff here

For me this is what works because I usually patch my classes a different way, using decorators like so:

import mock
from mock import patch
patch.object = patch.object

@patch.object(MyObject, 'methodName')
def test_foo(mockMethod):
    # do stuff here

If I used the # noinspection PyUnresolvedReferences trick here, it simply disabled this inspection for the entire function, not just for the @patch.object decorator... and I can't have that because I actually like to have those inspections tell me when I might be calling an unresolved reference.

like image 72
Ray Perea Avatar answered Oct 19 '22 23:10

Ray Perea