Making clean PR for Open Source Contributors ( PEP 8 Style )

Making clean PR for Open Source Contributors ( PEP 8 Style )

Code runs on local Pycharm IDE but throws Pylint / Deepsource error on Github repo.

·

5 min read

Are you new to open source contribution ? Does you code run on local machine but throws error(s) on making a PR (pull request) on some good GitHub repo? Then this article is for you. I have always had trouble in making a clean Pull Request on open source projects in python . And with time as the experience grew, it became even easier. Many Github repo with python follow PEP-8 style of coding. And a violation of these rules may throw some error which we neglect on local machine IDE.

We will broadly cover some of the error types in this article.

1. Use of global Statement

Anti Pattern It is recommended not to use global statement unless it is really necessary. Global variables are dangerous because they can be simultaneously accessed from multiple sections of a program. This frequently results in bugs.

stream = cv2.VideoCapture("clip.mp4")
flag = True
def play(speed):
    global flag
    print(f"You clicked on play. Speed is {speed}")

Fix- Create a basic read method, either as a class or a global function. Replace all reads with the access method, but leave the variable defined as a global. Review each of the writes to the method and extract action functions one at a time. Unless two operations are coded identically in the original code, extract each write access separately. Change the variable scope from global to local. Analyze similar action functions to determine if any can be merged, i.e., there are no functional differences in the results of the function, just differences in the implementation details. Review the calls to the read method and see if a more complex functionality should be applied. Follow the approach for writes and unless implementations are identical, create separate access functions. Analyze the access functions for duplication.

2. Imports

2.1 Multiple imports in one line (FLK-E401)

Imports should usually be on separate lines.

# Wrong Use
import os, sys

# Correct Use
import os
import sys

2.2 Module imported but unused PYL-W0611

Remove unused imports .

1.png

2.3 Unused import from wildcard import found PYL-W0614

In a wildcard import, all public names defined in the module are imported. It is advised to explicitly import the values needed or modify the module being imported from and define all to restrict the names to be imported.

2.png

3. Spaces

We will cover about idents and new line.

3.1 Bad indentation detected PYL-W0311

Style Statements use indentations that are not standard four spaces. PEP recommends 4 spaces to be used as a single indent.

# Wrong
else:
              print("hello")
# Correct
else:
    print("hello")

3.2 Blank line contains whitespace FLK-W293

Blank lines should not contain any tabs or spaces.

3.png

# correct one
 # Call this method to draw the button on the screen
if outline:
    pg.draw.rect(screen, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0)
pg.draw.rect(screen, self.color, (self.x,self.y,self.width,self.height),0)

   if self.text != '':

3.3 Trailing whitespace detected FLK-W291

There should be no whitespace after the final character in a line.

4.png

After the final word , please change the line to fix it.

3.4 Unexpected spaces around keyword / parameter equals (E251)

There should be no spaces before or after the = in a function definition.

# Anti Pattern
def fun(key1 = 'val1',
         key2 = 'val2'):
    return key1, key2
# Correct Use
def fun(key1='val1',
         key2='val2'):
    return key1, key2

3.5 Missing whitespace around operator FLK-E225

There should be one space before and after all operators.

# Anti Pattern
if age>15:
    print('Can drive')
# Correct Use
if age > 15:
    print('Can drive')

3.6 Missing whitespace after ',', ';', or ':' (E231)

# anti pattern
tup = 10,12,33
# correct one
tup = 10, 12, 33

3.7 At least two spaces before inline comment FLK-E261

Inline comments should have two spaces before them. Often programmers will only include one space, which will trigger this warning.

def print_name(self):
    print(self.name) # This comment needs an extra space
def print_name(self):
    print(self.name)  # Comment is correct now

3.8 Multiple blank lines detected at end of the file FLK-W391 / No newline at end of file FLK-W292

There should be one, and only one, blank line at the end of each file. This warning will occur when there are two or more blank lines.

#Wrong use
if __name__=="__main__":
    import ExampleButtons
#Wrong use
if __name__=="__main__":
    import ExampleButtons
#Correct use
if __name__=="__main__":
    import ExampleButtons

3.9 Function , Classes and Blank Spaces

Top-level function and classes are separated by two blank lines. Method definitions inside classes should be separated by one blank line. In the example , the classes SwapTest and OddOrEvenTest are separated by two blank lines, whereas the method definitions, such as .setUpSwap() and .test_swap_operation() only have one blank line to separate them.

class SwapTest(unittest.TestCase):
    """
        Swap Operation Test Case
    """
    def setUpSwap(self):
        self.a = 1
        self.b = 2

    def test_swap_operation(self):
        instance = Swap(self.a,self.b)
        value1, value2 =instance.get_swap_values()
        self.assertEqual(self.a, value2)
        self.assertEqual(self.b, value1)


class OddOrEvenTest(unittest.TestCase):
    """
        This is the Odd or Even Test case Suite
    """
    def setUp(self):
        self.value1 = 1
        self.value2 = 2

    def test_odd_even_operation(self):
        instance1 = OddOrEven(self.value1)
        instance2 = OddOrEven(self.value2)
        message1 = instance1.get_odd_or_even()
        message2 = instance2.get_odd_or_even()
        self.assertEqual(message1, 'Odd')
        self.assertEqual(message2, 'Even')

4 Unnecessary parentheses after keyword PYL-C0325

STYLE Extra parentheses in code can be removed for improved readability. In the examples below, the first example is more readable than the second one.

# Wrong Use
while(enter_screen):
    draw_enter()
    pg.display.update()
# Correct Use
while enter_screen:
    draw_enter()
    pg.display.update()

5 Line too long FLK-E501

Line length greater than configured max_line_length detected, defaults to 79 character. Real time issues and fixes.

Case 1 : 5.png Break after "," 6.png

Case 2 : 7.png Renaming folder comes to rescue 8.png

Case 3 : While using the + operator, you can better use a proper line break, which makes your code easier to understand:

total = A
        + B
        + C
# OR
total = (A +
         B +
         C)
# But not this
total = (A
         +   B
         +   C)

This is the first part of my tutorial on PEP-8 guidelines. I'm open to your suggestions.

Did you find this article valuable?

Support The STEM by becoming a sponsor. Any amount is appreciated!