Guidelines for young python developers – PART 2 | Fun with happy coding

NOTE: This part is independent and doesn’t require PART-1 to be referred compulsorily, but its advisable 🙂

Extended Slicing

Slicing in Python is a mechanism to select a range of items from Sequence types like strings, list, tuple, etc.

Syntax: [stat:end:step]

>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]
mylist[::-1] # will reverse a list

# Reverse a string
>>> S = 'Abhilash'
>>> S[::-1]
'haslihbA'

Method Overriding

In object oriented programming, language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes is called Method Overriding.

class Parent(object):
def __init__(self):
pass
def Create(self):
return 'Password'

class Child(Parent):
def __init__(self):
self.Create()
def Create(self):
return 'The ' + super(Child, self).Create()

print Child().Create() # prints "The Password"

So what exactly we are doing here; the class Child is capable of accessing the objects of class Parent, which is basically the base of the OOP concept.

Also you can see that class Child is also capable of overrides a method of the superclass, and you can also call the superclass method by calling super(Subclass, self).method instead of self.method.

Python Built-in Function – zip()

The Python’s built-in functions gives a lot more power to your program and there is an exhaustive list of that on Python Docs. We are not going to discuss them all, we will only see what zip power up’s.

zip() – A powerful function that can make your two lists paired together index wise and can give you option to do operations on both of them together.

# A simple example
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> z = zip(a,b)
>>> z
[(1, 4), (2, 5), (3, 6)]

# Lets do the same to iterate over two lists in parallel
>>> alist = ['a1', 'a2', 'a3']
>>> blist = ['b1', 'b2', 'b3']

>>> for a, b in zip(alist, blist):
print a, b
# Result
a1 b1
a2 b2
a3 b3

Static Method

@staticmethod is a Decorator. They are a special case of methods. Sometimes, you’ll write code that belongs to a class, but that doesn’t use the object itself at all. For example:

class Burger(object):
@staticmethod
def mix_ingredients(x, y):
return x + y

def cook(self):
return self.mix_ingredients(self.cheese, self.vegetables)

In such a case, writing mix_ingredients as a non-static method would work too, but it would provide it a self argument that would not be used.

So lets understand it in this way; python doesn’t have to instantiate a bound-method for each Burger object we instantiate. Bound methods are objects too, and creating them has a cost. Having a static method avoids that:

>>> Burger().cook is Burger().cook
False
>>> Burger().mix_ingredients is Burger.mix_ingredients
True
>>> Burger().mix_ingredients is Burger().mix_ingredients
True

Filter

The filter function constructs a list of elements from iterables for which the function returns true.

Let’s take a simple example where we want to remove all numbers which are less than 5.

n = [1,2,5,10,3,100,9,24]
a=[]
for e in n:
if e >= 5:
a.append(e)
n = a

# OR use filter
return filter(lambda x: x >= 5, n)

In the above piece of code, both the blocks will output same. But it makes the code look more simplified and easy to write.

What actually happening is the second block filter the list n with a condition x >=5. So once the condition is matched, it puts that particular element in x.

Built-in Exceptions

With Built-in-Exceptions, I am not really willing to demonstrate each and every Exception type python provides. My Intention is to grab your focus on this important topic too. This is very important to understand and practice to become a successful programmer. Error handling is a beauty which everyone should follow.

They are the heart of application behavioral science 😉

  • OverflowError
  • ZeroDivisionError
  • FloatingPointError
  • BufferError
  • IOError
  • OSError
  • AssertionError
  • KeyError
  • KeyboardInterrupt
  • MemoryError
  • RuntimeError
  • SyntaxError
  • SystemError
  • TypeError
  • RuntimeWarning

Lets have an example to demostrate it’s functionality:

(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
print "divide by zero"

So, the above code will catch the exception and handle it only for divisions happening with zero and others will be thrown with Tracebacks (And that very non-friendly).

However, all errors are widely the same as in other language, so python is not re-inventing the wheel. What’s important is to understand the usage and requirement of each to fully utilize the power.

You could refer Python Docs for the same, because this topic is something which require a dedicated separate blog. So start rolling!

Unittest

Testers love this. Companies are hiring specific people having this skill set. Testing word with big meaning for big standards. With unit testing each block of source code is set to be tested with pre-defined input and outputs. The task is to test that the program is doing what it is expected to do.

For an example: you may want to test a code blog with some specific filtration, like the data given by user should be converted into small case, the each character should be taken and converted into ASCII value and then returned. Just a random thought <:-|

Let’s see a more specific and direct example with codes. We need to check if a given text is palindrome or not, if word is palindrome then unit test will pass otherwise it will fail.

# Lets make our class and define method in it, that we will test later
class Process():
"""
Ideally this one should return a palindrome
But I have intentionally added another letter "A"
in end to make the method test to go false.
"""
&nbsp;   def CheckPalindrome(self,text=None):
# If we return this one, unit test will pass
Correct = text[::-1]

# If we return this one, unit test will fail
Wrong = text[1::-1]

return Wrong

Above code is a building block for converting  word into palindrome. So if we return Correct the unit test will pass and if we return Wrong the unit test will fail. Lets have a look at unit test code also.

import unittest

#Base class for Unit Testing
class TestFunctions(unittest.TestCase):
# Test case for checking Palindrome method
def test_CheckPalindrome(self):

# Expected input = "Abhilash"
TestOutput = CheckPalindrome("Abhilash")

# Expected output
ExpetedOutput = "hsalihbA"

self.assertEqual(ExpetedOutput, TestOutput)

#To auto instantiate the unit tests
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestFunctions)
unittest.TextTestRunner(verbosity=2).run(suite)

So if we consider the case we have defined above then CheckPalindrome will return “bA” and hence our condition will not match and a testError with Traceback will be shown.

Similarly, if we return Correct then it will give us test true and something like this will be a message on screen:

$ python unittest_simple.py -v

test (__main__.TestFunctions) ... ok
------------------------------------------------
Ran 1 test in 0.000s
OK

This abbreviated output includes the amount of time the tests took, along with a status indicator for each test. -v is for more detailed test results.

And of-course this is required in real world situation. Must for all programmers. Search for Test Driven Development (TDD), and start exploring.

cProfile

So what the heck is profiling? Profiling is a technique to dynamically examine and analyze programs and measure the time complexity, usage of different instructions, duration of function calls, memory complexity and so on.

Python includes a profiler called cProfile. It not only gives the total running time, but also times each function separately, and tells you how many times each function was called, making it easy to determine where you should make optimizations.

Lets have a look:

"""
You can call it from within your code,
or from the interpreter, like this:
"""
import cProfile
cProfile.run('foo()')

"""
Even more usefully, you can invoke the
cProfile when running a script:
"""
python -m cProfile myscript.py

"""
To make it even easier,
I made a little batch file called 'profile.bat':
"""
python -m cProfile %1

# So all I have to do is run:
profile euler048.py

And the output will be something like this:


Python is a beautiful language and its very robust. Keep learning as it actually drives lots of fun building products. Cheers!

If you have any suggestions or something that you wanna say to me, just Tweet me or DM me here.

If you enjoyed the article, please share it!

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments