Repository: MartinThoma/flake8-simplify (python)

Issue:
[Adjust Rule] SIM102: 'if __name__ == "__main__"' does not count
## Desired change

* **Rule(s)**: SIM102
* **Adjustment**: Ignore `if __name__ == "__main__"`

## Explanation

the check `if __name__ == "__main__"` is special. People recognize it as a special part of a script. Although one can combine things, I think it's better not to do it.

## Example

The following should not trigger SIM102

```python
if __name__ == "__main__":
    if foo(): ...
```


Pull request:
SIM102: Ignore 'if __name__ == "__main__"'
Closes #48


Patch:
diff --git a/flake8_simplify/rules/ast_if.py b/flake8_simplify/rules/ast_if.py
index 1756458..4136a26 100644
--- a/flake8_simplify/rules/ast_if.py
+++ b/flake8_simplify/rules/ast_if.py
@@ -9,7 +9,7 @@ from flake8_simplify.utils import get_if_body_pairs, is_body_same, to_source
 
 def get_sim102(node: ast.If) -> List[Tuple[int, int, str]]:
     """Get a list of all nested if-statements without else-blocks."""
-    SIM102 = "SIM102 Use a single if-statement instead of nested if-statements"
+    RULE = "SIM102 Use a single if-statement instead of nested if-statements"
     errors: List[Tuple[int, int, str]] = []
 
     # ## Pattern 1
@@ -31,7 +31,17 @@ def get_sim102(node: ast.If) -> List[Tuple[int, int, str]]:
 
     if not is_pattern_1:
         return errors
-    errors.append((node.lineno, node.col_offset, SIM102))
+    is_main_check = (
+        isinstance(node.test, ast.Compare)
+        and isinstance(node.test.left, ast.Name)
+        and node.test.left.id == "__name__"
+        and len(node.test.comparators) == 1
+        and isinstance(node.test.comparators[0], ast.Str)
+        and node.test.comparators[0].s == "__main__"
+    )
+    if is_main_check:
+        return errors
+    errors.append((node.lineno, node.col_offset, RULE))
     return errors
 
 


Test patch:
diff --git a/tests/test_100_rules.py b/tests/test_100_rules.py
index 44ed391..17f4cf7 100644
--- a/tests/test_100_rules.py
+++ b/tests/test_100_rules.py
@@ -54,13 +54,20 @@ def test_sim102_not_active1():
     assert ret == set()
 
 
-def test_sim102_not_active2():
-    ret = _results(
+@pytest.mark.parametrize(
+    "s",
+    (
+        """if __name__ == "__main__":
+    if foo(): ...""",
         """if a:
     d
     if b:
-        c"""
-    )
+        c""",
+    ),
+    ids=("__main__", "intermediate-statement"),
+)
+def test_sim102_should_not_trigger(s):
+    ret = _results(s)
     assert ret == set()