Python Interview Questions

Roy Smith roy at panix.com
Sun Nov 18 12:53:50 EST 2012


In article <50a911ec$0$29978$c3e8da3$5496439d at news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> Oh I'm sorry, did something I say suggest that the couple of examples I 
> gave are the *only* acceptable uses? My apologies for not giving an 
> exhaustive list of every possible use of lists and tuples, I'll be sure 
> to punish myself severely for the lapse.

Hmmm.  I didn't mean any offense.  I was just pointing out that what's 
true in theory and what's true in practice aren't always the same.

> Under what sort of circumstances would somebody want to take a mutable 
> list of data, say a list of email addresses, freeze it into a known 
> state, and use that frozen state as a key in a dict?

I've got a script which trolls our log files looking for python stack 
dumps.  For each dump it finds, it computes a signature (basically, a 
call sequence which led to the exception) and uses this signature as a 
dictionary key.  Here's the relevant code (abstracted slightly for 
readability):

def main(args):
    crashes = {}
    [...]
    for line in open(log_file):
        if does_not_look_like_a_stack_dump(line):
             continue
        lines = traceback_helper.unfold(line)
        header, stack = traceback_helper.extract_stack(lines)
        signature = tuple(stack)
        if signature in crashes:
            count, header = crashes[signature]
            crashes[signature] = (count + 1, header)
        else:
            crashes[signature] = (1, header)

You can find traceback_helper at 
https://bitbucket.org/roysmith/python-tools/src/4f8118d175ed/logs/traceba
ck_helper.py

The stack that's returned is a list.  It's inherently a list, per the 
classic definition:

* It's variable length.  Different stacks have different depths.

* It's homogeneous.  There's nothing particularly significant about each 
entry other than it's the next one in the stack.

* It's mutable.  I can build it up one item at a time as I discover them.

* It's ordered.  f1(f2()) is not the same as f2(f1()).

But, to use it as a dictionary key, I need to make it into a tuple, 
since keys have to be immutable.



More information about the Python-list mailing list