Search code examples
pythonpylintpep8

How to partially disable/ignore pylint rules?


Many of my scripts parse command line arguments inside the if __name__ == '__main__' block. I'm using 'normal' variable names there, e.g. parser. As this is not in any function, pylint will throw C0103: invalid constant name <variable>. Since I'm not really using those variables as constants (just parsing arguments), I'd find it a bit weird to use allcaps here.

Is there a way to partially disable pylint rules so as to not throw C0103 when inside the if __name__ == '__main__' block?

What I want is the following:

import argparse

PI = 3.14 # <--- should give no C0103
e = 2.71 # <-- should throw C0103

if __name__ == '__main__':
    parser = argparse.ArgumentParser() # <-- should give NO C0103
    PARSER = argparse.ArgumentParser() # <-- should optionally give C0103 (wrong variable name)

Thanks a lot :-).


Solution

  • This should be possible to achieve by wrapping the main method with pylint comments.

    import argparse
    # pylint: disable=C0103
    PI = 3.14 # <--- should give no C0103
    # pylint: enable=C0103
    e = 2.71 # <-- should throw C0103
    
    # pylint: disable=C0103
    if __name__ == '__main__':
        parser = argparse.ArgumentParser() # <-- should give NO C0103
        PARSER = argparse.ArgumentParser()
    # pylint: enable=C0103