Valuable recipe’s of core Python we love to skip part1

Blink fast - Imgur

Recipe 1:   Accessing private methods in python

Python doesn’t support privacy directly, but relies on the programmer to know when it is safe to modify an attribute from the outside. After all, you should know how to use an object before using that object. It is, however, possible to achieve something like private attributes with a little trickery.

To make a method or attribute private (inaccessible from the outside), simply start its name with two underscores:
class Secretive:
    def __inaccessible(self):
        print “Bet you can’t see me…”

    def accessible(self):
        print “The secret message is:”

Now __inaccessible is inaccessible to the outside world, while it can still be used inside the class (for example, from accessible):

>>> s = Secretive()
>>> s.__inaccessible()
Traceback (most recent call last):

File “<pyshell#112>”, line 1, in ?

AttributeError: Secretive instance has no attribute ‘__inaccessible’

>>> s.accessible()
The secret message is:
Bet you can’t see me…

Although the double underscores are a bit strange, this seems like a standard private method, as found in other languages. What’s not so standard is what actually happens. Inside a class definition, all names beginning with a double underscore are “translated” by adding a single underscore and the class name to the beginning:

>>> Secretive._Secretive__inaccessible
<unbound method Secretive.__inaccessible>
If you know how this works behind the scenes, it is still possible to access private methods outside the class, even though you’re not supposed to:
>>> s._Secretive__inaccessible()
Bet you can’t see me…

So, in short, you can’t be sure that others won’t access the methods and attributes of your objects, but this sort of name-mangling is a pretty strong signal that they shouldn’t.
If you don’t want the name-mangling effect, but you still want to send a signal for other objects to stay away, you can use a single initial underscore. This is mostly just a convention, but has some practical effects. For example, names with an initial underscore aren’t imported with starred imports.

Recipe 2: Dictionary methods you should know perfectly



The has_key method checks whether a dictionary has a given key. The expression d.has_key(k) is equivalent to k in d. The choice of which to use is largely a matter of taste, althoughhas_key is on its way out of the language (it will be gone in Python 3.0).
Here is an example of how you might use has_key:

>>> d = {}
>>> d.has_key(‘name’)
>>> d[‘name’] = ‘Eric’
>>> d.has_key(‘name’)

    items and iteritems

The items method returns all the items of the dictionary as a list of items in which each item is of the form (key, value). The items are not returned in any particular order:

>>> d = {‘title’: ‘Python Web Site’, ‘url’: ‘;, ‘spam’: 0} >>> d.items()
[(‘url’, ‘;), (‘spam’, 0), (‘title’, ‘Python Web Site’)]
The iteritems method works in much the same way, but returns an iterator instead of a list:

>>> it = d.iteritems()
>>> it

>>> list(it) # Convert the iterator to a list
[(‘url’, ‘;), (‘spam’, 0), (‘title’, ‘Python Web Site’)]
Using iteritems may be more efficient in many cases (especially if you want to iterate over the result). For more information on iterators, see Chapter 9.
keys and iterkeys
The keys method returns a list of the keys in the dictionary, while iterkeys returns an iterator over the keys.


The pop method can be used to get the value corresponding to a given key, and then remove the key-value pair from the dictionary:

>>> d = {‘x’: 1, ‘y’: 2}
>>> d.pop(‘x’)
>>> d
{‘y’: 2}


The popitem method is similar tolist.pop, which pops off the last element of a list. Unlike list.pop, however,popitem pops off an arbitrary item because dictionaries don’t have a “last element” or any order whatsoever. This may be very useful if you want to remove and process the items one by one in an efficient way (without retrieving a list of the keys first):

>>> d
{‘url’: ‘;, ‘spam’: 0, ‘title’: ‘Python Web Site’} >>> d.popitem()
(‘url’, ‘;)
>>> d
{‘spam’: 0, ‘title’: ‘Python Web Site’}

Although popitem is similar to the list method pop, there is no dictionary equivalent of append (which adds an element to the end of a list). Because dictionaries have no order, such a method wouldn’t make any sense.


The setdefault method is somewhat similar to get, in that it retrieves a value associated with a given key. In addition to the get functionality,setdefault sets the value corresponding to the given key if it is not already in the dictionary:

>>> d = {}
>>> d.setdefault(‘name’, ‘N/A’)
>>> d
{‘name’: ‘N/A’}
>>> d[‘name’] = ‘Gumby’
>>> d.setdefault(‘name’, ‘N/A’)
>>> d
{‘name’: ‘Gumby’}

As you can see, when the key is missing, setdefault returns the default and updates the dictionary accordingly. If the key is present, its value is returned and the dictionary is left unchanged. The default is optional, as with get; if it is left out,None is used:

>>> d = {}
>>> print d.setdefault(‘name’) None
>>> d
{‘name’: None}



The update method updates one dictionary with the items of another:

>>> d = {
‘title’: ‘Python Web Site’,
‘url’: ‘;,
‘changed’: ‘Mar 14 22:09:15 MET 2008’}
>>> x = {‘title’: ‘Python Language Website’}
>>> d.update(x)
>>> d
{‘url’: ‘;, ‘changed’:
‘Mar 14 22:09:15 MET 2008’, ‘title’: ‘Python Language Website’}

The items in the supplied dictionary are added to the old one, supplanting any items there with the same keys.
The update method can be called in the same way as the dict function (or type constructor), as discussed earlier in this chapter. This means that update can be called with a mapping, a sequence (or other iterable object) of (key, value) pairs, or keyword arguments.
values and itervalues
The values method returns a list of the values in the dictionary (anditervalues returns an iterator of the values). Unlike keys, the list returned by values may contain duplicates:

>>> d = {}
>>> d[1] = 1
>>> d[2] = 2
>>> d[3] = 3
>>> d[4] = 1
>>> d.values()
[1, 2, 3, 1]

Recipe 3: How nested functions in python can be used productively?

Python functions may be nested—you can put one inside another.2 Here is an example:
def foo():
    def bar():
        print “Hello, world!”

Nesting is normally not all that useful, but there is one particular application that stands out: using one function to “create” another. This means that you can (among other things) write functions like the following:

def multiplier(factor):
    def multiplyByFactor(number):
        return number*factor
    return multiplyByFactor

One function is inside another, and the outer function returns the inner one; that is, the function itself is returned—it is not called. What’s important is that the returned function still has access to the scope where it was defined; in other words, it carries its environment (and the associated local variables) with it!

Each time the outer function is called, the inner one gets redefined, and each time, the variable factor may have a new value. Because of Python’s nested scopes, this variable from the outer local scope (of multiplier) is accessible in the inner function later on, as follows:

>>> double = multiplier(2)
>>> double(5)
>>> triple = multiplier(3)
>>> triple(3)
>>> multiplier(5)(4)

A function such as multiplyByFactor that stores its enclosing scopes is called a closure. Normally, you cannot rebind variables in outer scopes. In Python 3.0, however, the keyword nonlocal is introduced. It is used in much the same way as global, and lets you assign to variables in outer (but nonglobal) scopes.

Recipe 4: Launching a webbrowser from a python program

The os.system function is useful for a lot of things, but for the specific task of launching a web browser, there’s an even better solution: the webbrowser module. It contains a function called open, which lets you automatically launch a web browser to open the given URL. For example, if you want your program to open the impythonist web site in a web browser (either starting a new browser or using one that is already running), you simply use this:

import webbrowser“;)

The page should pop up. Pretty nifty, huh?
        We will discuss lot more.Stay tuned. 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s