Skip to content

C1901 (compare-to-empty-string) message is not explicit about the problem and the solution #5234

@kfsone

Description

@kfsone

Bug description

Consider

   val_type, val_value = get_type(name)  # returns str, Any
   if val_type is Environment:
     if val_value is None or val_value is "":  # or ==

The last line produces a pylint error, with the common guidance (e.g https://vald-phoenix.github.io/pylint-errors/plerr/errors/compare-to-empty-string/C1901.html) suggesting that you should use:

    if val_value is None or not len(val_value):

The user used val_value is "" to explicitly say: is it a string, and is it empty?

To avoid doing this is or == comparison, the user would need to write:

    if val_value is None or (isinstance(val_value, str) and not len(val_value)):

example of following the guidance too literally:

    def fn(v):
      if len(v):
          return "empty"
      return "other"

    fn(None)    # OK: returns "other"
    fn("a")     # OK: returns "other"
    fn([None])  # OK: returns "other"
    fn("")      # OK: returns "empty"
    fn([])      # WRONG: returns "other"
    fn(0)       # ERROR: int has no len

Configuration

No response

Command used

pylint a.py

Pylint output

a.py.3.1: [C1901(compare-to-empty-string), a.py] Avoid comparisons to empty string [229,1]

Expected behavior

This should either be disabled by default or it should provide better guidance. Why is x is "" bad?

Pylint version

pylint 1.9.5,
astroid 1.6.6
Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)]

OS / Environment

No response

Additional dependencies

No response

Metadata

Metadata

Labels

Documentation 📗Good first issueFriendly and approachable by new contributorsHacktoberfestHelp wanted 🙏Outside help would be appreciated, good for new contributorsNeeds PRThis issue is accepted, sufficiently specified and now needs an implementation

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions