Python Cookbook

Category: Programming
Author: Alex Martelli, Anna Ravenscroft, David Ascher
3.9
All Stack Overflow 7
This Year Stack Overflow 2
This Month Stack Overflow 2

About This Book

Portable, powerful, and a breeze to use, Python is the popular open source object-oriented programming language used for both standalone programs and scripting applications. It is now being used by an increasing number of major organizations, including NASA and Google.Updated for Python 2.4, The Python Cookbook, 2nd Edition offers a wealth of useful code for all Python programmers, not just advanced practitioners. Like its predecessor, the new edition provides solutions to problems that Python programmers face everyday.It now includes over 200 recipes that range from simple tasks, such as working with dictionaries and list comprehensions, to complex tasks, such as monitoring a network and building a templating system. This revised version also includes new chapters on topics such as time, money, and metaprogramming.

 

Here's a list of additional topics covered:

  • Manipulating text
  • Searching and sorting
  • Working with files and the filesystem
  • Object-oriented programming
  • Dealing with threads and processes
  • System administration
  • Interacting with databases
  • Creating user interfaces
  • Network and web programming
  • Processing XML
  • Distributed programming
  • Debugging and testing

Another advantage of The Python Cookbook, 2nd Edition is its trio of authors--three well-known Python programming experts, who are highly visible on email lists and in newsgroups, and speak often at Python conferences.With scores of practical examples and pertinent background information, The Python Cookbook, 2nd Edition is the one source you need if you're looking to build efficient, flexible, scalable, and well-integrated systems.

Comments

by anonymous   2019-07-21

Here is the example in Alex Martelli Python Cookbook that show how to create a memoize decorator using cPickle for function that take mutable argument (original version) :

import cPickle

class MemoizeMutable:
    def __init__(self, fn):
        self.fn = fn
        self.memo = {}
    def __call__(self, *args, **kwds):
        import cPickle
        str = cPickle.dumps(args, 1)+cPickle.dumps(kwds, 1)
        if not self.memo.has_key(str): 
            print "miss"  # DEBUG INFO
            self.memo[str] = self.fn(*args, **kwds)
        else:
            print "hit"  # DEBUG INFO

        return self.memo[str]

Here is a link.

EDIT: Using the code that you have given and this memoize decorator :

_level = MemoizeMutable(_level)

equirements = {'a': [],
               'b': [],
               'c': ['a'],
               'd': ['a','b'],
               'e': ['c','d'],
               'f': ['e']
                 }

print uses_hierarchy(equirements)

i was able to reproduce this:

miss
miss
hit
miss
miss
hit
miss
hit
hit
hit
miss
hit
{0: ['a', 'b'], 1: ['c', 'd'], 2: ['e'], 3: ['f']}
by anonymous   2019-07-21

Programming language teaching has always been associated with a cliche statement while learning. "Write programs to learn programming". I too would suggest the same.

If you are going to start from basics. This is of course, the most suggested starting point. It is lengthy, but it is worth all the time. http://www.diveintopython.org/

Because you are into some Java, this might be even better for you. http://www.swaroopch.com/notes/Python. Start either python 2.x or 3.0. Me personally am a fan of python 3. But for a starter it could be hard to get samples, and references to programs online. So for you 2.x might be better. But I leave it upto you.

Like I started "Write programs..". You can start here.

  1. http://www.spoj.pl/ - a programming challenges site, where you can choose from a wide variety of topics, mostly algorithms and has huge question database. Of course the choice of programming languages is upto you.
  2. http://projecteuler.net/ - a mathematical questions site, here you just have to submit an answer, cheating is allowed here, so be free to borrow logic from others, but try writing the program yourself.

After you think you have gained sufficient proficiency in python, you can try recipes in this book python cookbook http://www.amazon.com/Python-Cookbook-Alex-Martelli/dp/0596007973.

For application development, after you think you can handle it, start on wxPython or PyQt. I personally would suggest PyQt. It is responsive, fast, and has decent development cycle, I have not used WxPython for long, but few programs I wrote, long back, didn't feel so great. Yet again, its upto you.

by anonymous   2017-08-20

Have you read the Python Cookbook? It's a pretty good source for Pythonic.

Plus you'll find much more from Alex Martelli on Stack Overflow.

by technomalogical   2017-08-20

+1 for Dive into Python and Python in a Nutshell. I also highly recommend effbot's Guide to the Standard Library. You'll probably also want to check out the Python Cookbook for some good examples of idiomatic Python code. Check out Foundations of Python Networking to pick up where the SysAdmin book leaves off in terms of network protocols (fyi: all APress books are available as PDFs, which I love)

by anonymous   2017-08-20

What you are looking for is Denis Otkidach's excellent CachedAttribute:

class CachedAttribute(object):    
    '''Computes attribute value and caches it in the instance.
    From the Python Cookbook (Denis Otkidach)
    This decorator allows you to create a property which can be computed once and
    accessed many times. Sort of like memoization.
    '''
    def __init__(self, method, name=None):
        # record the unbound-method and the name
        self.method = method
        self.name = name or method.__name__
        self.__doc__ = method.__doc__
    def __get__(self, inst, cls):
        # self: <__main__.cache object at 0xb781340c>
        # inst: <__main__.Foo object at 0xb781348c>
        # cls: <class '__main__.Foo'>       
        if inst is None:
            # instance attribute accessed on class, return self
            # You get here if you write `Foo.bar`
            return self
        # compute, cache and return the instance's attribute value
        result = self.method(inst)
        # setattr redefines the instance's attribute so this doesn't get called again
        setattr(inst, self.name, result)
        return result

It can be used like this:

def demo_cache():
    class Foo(object):
        @CachedAttribute
        def bar(self):
            print 'Calculating self.bar'  
            return 42
    foo=Foo()
    print(foo.bar)
    # Calculating self.bar
    # 42

Notice that accessing foo.bar subsequent times does not call the getter function. (Calculating self.bar is not printed.)

    print(foo.bar)    
    # 42
    foo.bar=1
    print(foo.bar)
    # 1

Deleting foo.bar from foo.__dict__ re-exposes the property defined in Foo. Thus, calling foo.bar again recalculates the value again.

    del foo.bar
    print(foo.bar)
    # Calculating self.bar
    # 42

demo_cache()

The decorator was published in the Python Cookbook and can also be found on ActiveState.

This is efficient because although the property exists in the class's __dict__, after computation, an attribute of the same name is created in the instance's __dict__. Python's attribute lookup rules gives precedence to the attribute in the instance's __dict__, so the property in class becomes effectively overridden.