Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Thursday, November 8, 2012

python: tips and tricks

1.

m = {'a': 1, 'b': 2}

m[ 'c' ] will throw error. Instead use m.get( 'c', 'default' )

2.

'foo'.index( 'bar' ) throws Exception

'foo'.find( 'bar' ) returns -1

Tuesday, October 30, 2012

python: import a custom file

suppose you wrote a python file with common functions, say util.py and you want use it in another of your python files

If they in the same directory the below should work

import util

If they in different directories the below will not work. To make it work add another entry

sys.path.append('<path/to/the/folder/of/util.py>')
import util

This fixes it. This is the simplest way to me but there must be more.I will explore it further and update.

python: import function

This is interesting to me. We can import only a particular function of a module inside python

Say there is a function boto.ec2.regions()

So I would write

>>> import boto.ec2
or
>>> from boto import ec2

>>> boto.ec2.regions()
or
>>> ec2.regions()

But we can also write

>>> from boto.ec2 import regions

>>> regions()

I had this scenario. Inside my python file I had import my util file. In the util file I had the above import.

from boto.ec2 import regions

So in my python file I could write

import util

util.regions()

Awesome right??