Skip to main content


Showing posts with the label Python

Numpy...why so serious?

What can we really do with Numpy? Why should we use it at all ?

Start with : import numpy

1. We can create arrays .
method: numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

>>> a = numpy.array(range(10)) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> a.dtype dtype('int32')
In the above array, there are 10 columns and 1 row.

Note : The concept of rows and columns applies when you have a 2D array. However, the array numpy.array([1,2,3,4]) is a 1D array and so has only one dimension, therefore shape rightly returns a single valued iterable.

Refer this link

2. We can create/convert array of a particular type (immediate conversion of your list to a desired type)

>>> s = numpy.array(range(10), dtype=str) >>> s array(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], dtype='|S1')-------------------------------…

Test server that accepts GET/POST calls using Python Flask

I was trying out Flask. In the process, I made a website that behaves like a server. It can help you test GET and POST calls.

It goes like this .

fromflaskimport Flask, request app = Flask(__name__) @app.route('/method', methods=['GET', 'POST']) @app.route('/method/<wish>', methods=['GET', 'POST']) defmethod_used(wish=None): if request.method =='GET': if wish: if wish indir(request): ans =None s ="ans = str(request.%s)"% wish exec s return ans else: return'This wish is not available. The following are the available wishes: %s'% [method for method indir(request) if'_'notin method] else: return'This is just a GET method'else: return"You are using POST"
When I run this, this…

How to test POST call using Python?

I got into a situation recently where I needed to test if my POST function was indeed working.

Its easy to test GET method . You just visit the URL and that's it . But for POST, you an use PlugIns.

But unfortunately I can't do that , because my browser (admin restrictions ) doesn't allow me to install plugins . Fortunately if you have Python , you can easily do that .

The request module is a handy module when it comes to testing web responses etc. It also has support for POST methods. You can literally fill a form using this . Let's test our url .

This is our POST method. (Its a Flask code).

@app.route('/method',methods=['GET','POST'])defmethod_used():ifrequest.method=='GET':return"Method used: %s"%request.methodelse:return"You are using POST"
So if its a GET method, the response we expect is Method used: GET . And if its a POST method, we expect "You are using POST"

Now lets bring out the request module. I have ru…

Writing context managers using Python

We use. We forget. This is for myself so I remember the magic called Context Manager. You already must have used the "with statement" for file handling, threads, socket and other operations. I am going to talk about creating you OWN context managers.

The magic operator to be used is : @contextmanager. It can be imported from the module "contextlib"

To create a context manager, use the decorator contextlib.contextmanager

@contextlib.contextmanagerdefgetListCounts(x): try: fromcollectionsimport Counter yield Counter(x) finally: print'No of elements in the list : %d' % len(x)

Let's now use the above context manager 

Example 1:
>>> with getListCount([10, 10, 12]) as c: print "Element occurring the most is %d" % c.most_common()[0][0] Element occurring the most is 10 No of elements in the list : 3
Example 2:
>>> with getListCount([10, 10, 12]) as c: print "Element occurring the least is %d"…

Python: Super class examples

Hi all. We are going to see some examples of usage of keyword 'super' here . 
Below code shows two classes Employee and Developer. A parent and a child.

classEmployee(object):def__init__(self,first,last):self.first=firstself.last=lastprint'Employee: {0}, {1}'.format(first,last)defhike_category(self):hike=0ifself.grade=='A':hike=(0.1*'B':hike=(0.15*'C':hike=(0.20*'{0},{1} gets {2}'.format(self.first,self.last,hike)classDeveloper(Employee):def__init__(self,fname,lname,grade,pay):super(Developer,self).__init__(fname,lname)
Lets run the above program.


>>> d = Developer('arc', 'roy', 'C', 10000) Employee: arc, roy >>> d.hike_category() 'arc,roy gets 12000.0'
Observations and things to note
Above programming is done in Python 2.7. In 2.7, the class …

Quick guide to Logging in different files using Python

This is for quick setup of a logging system . 
Step 1: import logging 
Logging is the build-in module for implementing logging in Python.

Step 2: Create a logger for yourself. 
logger = logging.getLogger(__name__)

Step 3: Set Logger level

Step 4: Create a handler. 
hdlr = logging.FileHandler(settings.BASE_LOG_FILE, mode='w')

Step 5: Create a formatter
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

Step 6: Set formatter and handler


When and why to use Classes in Python

Note: All programming done in Python 2.7

Why to make a class?

When we need to use some common variables across other functions quite often . If we only one or 2 functions to write , we should not need to write a class. But if we are going to have 4-5 functions that need to use common objects between themselves, then its better to use classes.

What are class methods?

Class methods are methods that you can call on the class itself

A good example of classes . Lets have a BankAccount class for managing Bank Accounts and its related operations.

classBankAccount(object):#Class methods are methods that you can call on the class itselfdef__init__(self,balance=0):self.balance=balancedefdeposit(self,amount):self.balance+=amountdefwithdraw(self,amount):self.balance-=amount
The __init__ functionis automatically called when a new instance is created. We have two functions that add or subtract  money from account.

Ok....So lets create 2 accounts

Now lets …

Generator functions. Why and when should we use them.

You probably have heard of them. But as a beginner python programmer, we tend to ignore it's values because we fail to find uses of it. When we have loops and itertools and other fancy toys offered, why should we bother to understand them. If you want to take your programming  or understanding of Python to the next level, you must understand and use generators more and more.

Before we start, I want to make a simple program that prints square of (hence generates and delivers) 5 numbers from 1 to 5. So what is the first idea that pops up ? Let's use a forloop.

defsquare(N): for i inrange(1, N+1): print i**2>>>square(5) 1491625
Let's say, you need all the values generated for some other calculation. I know, above example is too lame . But imagine after some complicated calculations, you have generated some result.
So you probably will return all values together in an array. And to that, the first thought in our minds is, using a LIST. Let's use it. 

Now ou…

Python: Running executables using subprocess module

There are many ways to run a bat/exe file but the most widely used is the subprocess module.
And I would like to clearly show, how exactly to do that. When should you use what arguments.
I am going to specifically talk about the check_output module .

Note : This function is used when we want the output of the bat file collected inside a variable.

Condition 1: The exe file is in the same location as of the python script that wants to run it.

You are in a Folder > MyPrograms  . And the bat/exe file lies inside this folder. (Refer picture below)

Content of the hello.bat file

@echooffecho"This is a test bat"

My script contents:

importsubprocess result = subprocess.check_output('hello.bat') print result

Now if you run it , the result will be a:

"This is a test bat"
This is easy. Let's look at another condition.

Condition 2: The exe file is in a different location from the python script that wants to run it.

No change in contents of hello.bat file…

Regular Expressions with Python: Look ahead and Look behind

These two important tools have been bugging me every time I come up with a situation. Because I never remember this one. Blame my memory.
So it's time I cement this idea somewhere . And no better place than a blog page.

LOOK AHEADLOOK AHEAD means , I want to see what lies ahead first, and then decide, to do something now.
Syntax of regex pattern:pattern1(?=pattern2)

Where Pattern1 is the pattern for the part that we ACTUALLY want to capture. Pattern2 is the pattern which needs to be found as MANDATORY. Logically speaking, 
IFPATTERN2isFOUND, then print/get/capture/show PATTERN1

Example: Let there be a string "Hello World"
Aim: I want to find 'Hello' ...ONLY IF its followed by 'World''\w+(?= World)', 'Hello World').group()
Result : >> 'Hello'
 The \w+ is Pattern1 The 'World' is Pattern2 r'\w+(?= World)' means, Find anything which fits \w+ IF it is followed by 'World'
The Pattern2 …