Search code examples
pythonfilepython-3.xundefinedpylint

undefined-variable Warning for python 3.x in pylint


I am writing a python script but I just faced this issue regarding pylint checks in python 3.x :

class m(object):
    def check_infile(self):
        infile = None
        if not isinstance(infile, file):
            print("infile variable is not a file type.")

Output:

E: 56,38: Undefined variable 'file' (undefined-variable)

I tried to eliminate this issue by adding # pylint: disable=E0602, undefined-variable, E0603 but nothing helps. any suggestion?


Solution

  • In python3.x, file isn't a valid type:

    Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
    [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> file
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'file' is not defined
    

    So pylint is right here and you probably don't want to silence it. You might want to check if the object has file-like methods:

    if not getattr(infile, 'read', None):
        print('definitely not a file...')