Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

05 July 2011

Java String comparison

A common mistake you might make when doing Java string comparison is like this:

String s = "abs";
String t = "cde";

// test for pointer equality, in other words,
// test if s and t are the same object
if (s == t)


What you really want to do might be this:

if (s.equals(t)) // compare characters in two strings


However in python, s==t is actually what you want. When you know too many programming languages, you can easily mess up the syntax and semantics of them accidentally. Be careful.

06 May 2011

Python datetime object

A little note about datetime object: date, datetime, time objects all support a strftime(format) method. Check its document here. And you can see some concrete code examples (about the time format).

Google App Engine Blobstore API experience

I have been building a small website in the past few days using Google App Engine. During this small project, the most intriguing part is hacking Blobstore API. Luckily, I conquered it again and found a few things:

  1. To create your own blob in blobstore, you'd better follow this example
  2. If you follow that example exactly, you will create a blob without filename. To set the filename when creating a blob, I found this discussion; the original google api document isn't very helpful on that. To get more insights about that API, check the source code here.

05 January 2011

Python raw_input() vs input()

# raw_input() reads every input as a string
# then it's up to you to process the string

str1 = raw_input("Enter anything:")
print "raw_input =", str1

# input() actually uses raw_input() and then tries to
# convert the input data to a number using eval()
# hence you could enter a math expression
# gives an error if input is not numeric eg. $34.95

x = input("Enter a number:")
print "input =", x


The code example above is from this link. One other thing to note here is that there is no raw_input in Python 3 anymore, only input() function available.

16 November 2010

Python inheritance examples

Here are a few links that provide examples for Python inheritance:

http://www.wellho.net/solutions/python-inheritance.html
http://tinyurl.com/q9ambl

The only thing to note is to use super() with caution.

The best way of checking empty list or dict in Python

There must be an idiom for this task. Here is how I test such conditions:

d = {} # an empty dictionary
l = [] # an empty list

bool(len(l)) # False
not len(l)   # True

bool(len(d)) # False
not len(d)   # True


Or, an even neater way to do it:


d = {} # an empty dictionary
l = [] # an empty list

bool(d) # False, the empty dict is converted to bool directly!
not d   # True

# So, you can have something like this:

if not d: doSomething()

Python toString() class method?

Again, this is a common question regarding to Python OOP. In Java, we often overwrite a class method toString() for our own class, is there an equivalent thing in Python?

The answer is ... YES!

Just by redefining an special "__str__(self):" method in your own class, you can have your own human-readable string representation of your class object! What a beauty!

How to, in Python, iterate through 2D list at once clearly?

I found that this problem is frequently occurred during my python software development. Therefore I did a bit of research and found this link: http://tinyurl.com/2czv57z

So, one neat solution is to use functions in itertools module. Here is how:

from itertools import izip
  for a_row,b_row in izip(alist, blist):
    for a_item, b_item in izip(a_row,b_row):
      if a_item.isWhatever:
        b_item.doSomething()

27 October 2010

Yet another web development framework - web.py

Posted from Diigo. The rest of my favorite links are here.

Web.py lets you write web apps in python while Django lets you write web apps in Django.

Python decorator

It sounds intimidating at first because other OO languages like C++ or Java doesn't have such concept or construct built in. So what's about it?

def dec_func():
   ...

@dec_func
def func():
   ...


function 'func' is being decorated by function 'dec_func'; it is equivalent to "func = decf_func(func)".


The key concept is this:

@ is just a little syntax sugar meaning "pass a function object through another function and assign the result to the original function."

It brings the idea of "applying code to other code" (i.e.: like C macros) into mainstream thinking by formalizing it as a language construct. See the link

25 October 2010

Python class attributes v.s. data attributes

In Java, both static variables (called class attributes in Python) and instance variables (called data attributes in Python) are defined immediately after the class definition (one with the static keyword, one without). In Python, only class attributes can be defined here; data attributes are defined in the __init__ method.

Class attributes can be used as class-level constants, but they are not really constants.

Python supports data attributes (called “instance variables” in Java and “member variables” in C++). Data attributes are pieces of data held by a specific instance of a class. To reference this attribute from code outside the class, you qualify it with the instance name, instance.data, in the same way that you qualify a function with its module name. To reference a data attribute from within the class, you use self as the qualifier. By convention, all data attributes are initialized to reasonable values in the __init__ method. However, this is not required, since data attributes, like local variables, spring into existence when they are first assigned a value.

Vim code tab-completion support for python

Ever felt disappointed when writing codes in Vim but without code completion functionality just like what Eclipse IDE has? Well, Vim 7+ can do auto-completion by default!

In the insert mode (i-mode), when you press [ctrl]+p or [ctrl]+n, vim will try to complete with words that have already appeared in the current file. But that's it, that is the default.

To make vim even smarter, we have to teach him how to complete other words. The idea is using 'dictionaries'. Fortunately, some guys out there have already developed plugins (for code completion) for certain programming languages. Here I am going to show you vim plugin support for python.

First, download the plugin package (pydiction) from here:

http://www.vim.org/scripts/script.php?script_id=850

Second, unpack the package and basically put files inside ~/.vim directory.

Third, if you are downloading pydiction 1.0+, just follow the installation instructions in the README.txt inside the package, or read instructions from the link listed above. However if you are downloading packages below 1.0, then follow instructions here:

http://tinyurl.com/balbal

Now you can do tab-completion for python codes! This tool should accelerate your programming speed in Vim. Try it and stop complaining!

22 October 2010

Python singleton design pattern

How to define a class with a singleton instance? From http://python.org/dev/peps/pep-0318/, here is how:

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    ...


However, you can also achieve singleton without such clumsy code - use python module. See here:

http://tinyurl.com/yeotybq.

A module with functions and module scope variables is handy for such purpose! So no OOP is needed?! However, be cautious with singleton design pattern. Watch this blog post from google testing blog.

Python private functions

If the name of a Python function, class method, or attribute starts with (but doesn't end with) two underscores, it's private; everything else is public. Python has no concept of protected class methods; class methods are either private or public.

The privateness are implemented through a special renaming tricks done by python interpreter/compiler:

Variable __var in class cls gets replaced by _cls__var by compiler!

05 September 2010

Common tasks in Python

Common tasks including:
  1. Traversing file system - os.listdir(dir)
  2. Getting file path name - 
    • os.path.join(dir, filename): return a path that puts dir and filename together
    • os.path.abspath(path): return the absolute path name of path
  3. Test file/directory existence - os.path.exists(path)
  4. Create directories - os.mkdir(dir_path)
  5. High level file operations - shutil module ; in particular file copying and removal
  6. Running other commands from within python program - commands module
    • commands.getstatusoutput(cmd) : return a tuple (status, output)
    • commands.getoutput(cmd)
  7. Downloading a web page from an url to a local file - urllib module:
    • urllib.retrieve(url, local_dst_path)
        Reference at:
        http://docs.python.org/library/commands.html
        http://docs.python.org/library/shutil.html
        http://code.google.com/edu/languages/google-python-class/utilities.html
        http://docs.python.org/library/urllib.html

        03 September 2010

        Python ord() and chr() built-in functions

        http://docs.python.org/library/functions.html#ord
        http://docs.python.org/library/functions.html#chr

        They are each other's inverse function. Both of them are handy for obtaining ASCII values of a Unicode character.

        Must@p Zone


        Posted from Diigo. The rest of my favorite links are here.

        28 August 2010

        Python file hack


          # Echo the contents of a file
          f = open('foo.txt', 'rU')
          for line in f:   ## iterates over the lines of the file
            print line,    ## trailing , so print does not add an end-of-line char
                           ## since 'line' already includes the end-of line.
          f.close()

        The special mode 'rU' is the "Universal" option for text files where it's smart about converting different line-endings so they always come through as a simple '\n'. This is a really useful hack about reading files that have heterogeneous line formats!

        18 August 2010

        Python __init__ and __new__

        What is the difference between __init__ and __new__?

        Each NEW-style python class has (or inherits from object class) a static method (can be called without creating an object) named __new__. When you call C(*args, **kwds) to create a new instance of class C, Python first calls C.__new__(C, *args, *kwds). Python uses __new__'s return value x as the newly created instance. Then Python calls C.__init__(x, *args, **kwds), but only when x is indeed an instance of C or any of its subclasses.

        Thus, the statement x=C(23) is equivalent to:


        x = C.__new__(C, 23)
        if isinstance(x, C): type(x).__init__(x, 23)


        So basically, __new__ is just like new keyword in Java; __new__ and __init__ combine together provide the functionality of an object constructor!

        16 August 2010

        Python sort() method


          alist.sort()            ## correct
          alist = blist.sort()    ## NO incorrect, sort() returns None

        The above is a very common misunderstanding with sort() - It DOES NOT return the sorted list. It returns None.