Wednesday, February 17, 2010

comp.lang.python - 25 new messages in 8 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* error trying to join #python on irc.freenode.net - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/6f73186707aafacb?hl=en
* string to list when the contents is a list - 5 messages, 5 authors
http://groups.google.com/group/comp.lang.python/t/d604be2eee402ced?hl=en
* Interesting talk on Python vs. Ruby and how he would like Python to have
just a bit more syntactic flexibility. - 11 messages, 6 authors
http://groups.google.com/group/comp.lang.python/t/9a88c79d4043ba30?hl=en
* Which mock library do you prefer? - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/a12daa9de8354ff2?hl=en
* How to efficiently extract information from structured text file - 2
messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/bc8840f8a254056b?hl=en
* Wrap and intercept function calls - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/8785a4e8d85dd581?hl=en
* Draft paper submission deadline is extended: SETP-10, Orlando, USA - 1
messages, 1 author
http://groups.google.com/group/comp.lang.python/t/b8af1aeb393da22a?hl=en
* Traversing through variable-sized lists - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/6f56c35ab7103a91?hl=en

==============================================================================
TOPIC: error trying to join #python on irc.freenode.net
http://groups.google.com/group/comp.lang.python/t/6f73186707aafacb?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 3:56 pm
From: Wes James


On Wed, Feb 17, 2010 at 4:53 PM, Wes James <comptekki@gmail.com> wrote:
> When I try to join #python on irc.freenode.net it keeps saying:
>
> You need to identify with network services to join the room "#python"
> on "irc.freenode.net".
>
> Server Details:
> Cannot join channel (+r) - you need to be identified with services
>
> What does this mean?


Nevermind, I think it means I need to register with the service and
supply real username/password.

-wes

==============================================================================
TOPIC: string to list when the contents is a list
http://groups.google.com/group/comp.lang.python/t/d604be2eee402ced?hl=en
==============================================================================

== 1 of 5 ==
Date: Wed, Feb 17 2010 4:08 pm
From: Vlastimil Brom


2010/2/18 Wes James <comptekki@gmail.com>:
> I have been trying to create a list form a string.  The string will be
> a list (this is the contents will look like a list).  i.e. "[]" or
> "['a','b']"
>
> The "[]" is simple since I can just check if value == "[]" then return []
>
> But with "['a','b']" I have tried and get:
>
> a="['a','b']"
>
> b=a[1:-1].split(',')
>
> returns
>
> [ " 'a' "," 'b' " ]
>
> when I want it to return ['a','b'].
>
> How can I do this?
>
> thx,
>
> -wes
> --
> http://mail.python.org/mailman/listinfo/python-list
>

The potentially problematic exec or eval options left aside,
if you really need to do this, you might consider pyparsing; check the example
http://pyparsing.wikispaces.com/file/view/parsePythonValue.py

If you know, the input string will always have this exact format
(single quoted comma separated one-character strings between square
brackets), you might use regular expressions to some extent, e.g.

print re.findall(r"(?<=')\w(?=')", "['a','b','c','b','A']")
['a', 'b', 'c', 'b', 'A']

hth,
vbr


== 2 of 5 ==
Date: Wed, Feb 17 2010 4:13 pm
From: "Rhodri James"


On Wed, 17 Feb 2010 23:48:38 -0000, Wes James <comptekki@gmail.com> wrote:

> I have been trying to create a list form a string. The string will be
> a list (this is the contents will look like a list). i.e. "[]" or
> "['a','b']"

If your string is trusted (i.e. goes nowhere near a user), just eval() it.

--
Rhodri James *-* Wildebeeste Herder to the Masses


== 3 of 5 ==
Date: Wed, Feb 17 2010 4:47 pm
From: Steven D'Aprano


On Thu, 18 Feb 2010 00:13:05 +0000, Rhodri James wrote:

> On Wed, 17 Feb 2010 23:48:38 -0000, Wes James <comptekki@gmail.com>
> wrote:
>
>> I have been trying to create a list form a string. The string will be
>> a list (this is the contents will look like a list). i.e. "[]" or
>> "['a','b']"
>
> If your string is trusted (i.e. goes nowhere near a user), just eval()
> it.

Or use something like YAML or JSON to parse it.

Fredrik Lundh has a simple_eval function which should be safe to use:

http://effbot.org/zone/simple-iterator-parser.htm


But it's fairly simple to parse a simple list like this. Here's a quick
and dirty version:


def string_to_list(s):
s = s.strip()
if not s.startswith('[') and s.endswith(']'):
raise ValueError
s = s[1:-1].strip()
items = [item.strip() for item in s.split(',')]
for i, item in enumerate(items):
items[i] = dequote(item)
return items


def dequote(s):
for delimiter in ('"""', "'''", '"', "'"):
if s.startswith(delimiter) and s.endswith(delimiter):
n = len(delimiter)
return s[n:-n]
raise ValueError

>>> s = "['a','b']"
>>> print s
['a','b']
>>> string_to_list(s)
['a', 'b']
>>> x = string_to_list(s)
>>> type(x)
<type 'list'>
>>> x
['a', 'b']

--
Steven


== 4 of 5 ==
Date: Wed, Feb 17 2010 4:51 pm
From: Matt McCredie


Wes James <comptekki <at> gmail.com> writes:

>
> I have been trying to create a list form a string. The string will be
> a list (this is the contents will look like a list). i.e. "[]" or
> "['a','b']"
>
> The "[]" is simple since I can just check if value == "[]" then return []
>
> But with "['a','b']" I have tried and get:
>
> a="['a','b']"
>
> b=a[1:-1].split(',')
>
> returns
>
> [ " 'a' "," 'b' " ]
>
> when I want it to return ['a','b'].
>
> How can I do this?


eval will work, but has a safety issue. It also has the issue of evaluating any
and everything that a user might pass in.

If you are using python 2.6 check out ast.literal_eval. It uses python's built
in ast parser to generate an AST and then traverses it to generate a python
object. Unlike eval though, it will raise an exception if anything other than a
literal is represented in the string. I have used the same function in python
2.5 (copied from 2.6) and it works just fine.

Here is a version modified from the code in python 2.6 that should only parse
lists of strings:

from _ast import List, Str, PyCF_ONLY_AST

def parse(expr, filename='<unknown>', mode='exec'):
"""
Parse an expression into an AST node.
Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST).
"""
return compile(expr, filename, mode, PyCF_ONLY_AST)


def list_eval(text):
"""
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
"""

node = parse(text, mode='eval').body
if not isinstance(node, List):
raise ValueError('malformed string')
def _convert(node):
if isinstance(node, Str):
return node.s
raise ValueError('malformed string')

return list(map(_convert, node.elts))


Matt McCredie

== 5 of 5 ==
Date: Wed, Feb 17 2010 4:58 pm
From: Ben Finney


Wes James <comptekki@gmail.com> writes:

> I have been trying to create a list form a string. The string will be
> a list (this is the contents will look like a list). i.e. "[]" or
> "['a','b']"

Pulling back to ask about the larger problem: Are you trying to create
Python data structures from a serialised representation?

There are several well-implemented solutions, including the standard
library modules 'pickle' and 'json'. Do you have control over the choice
of serialisation format?

--
\ "I went to court for a parking ticket; I pleaded insanity. I |
`\ said 'Your Honour, who in their right mind parks in the passing |
_o__) lane?'" —Steven Wright |
Ben Finney

==============================================================================
TOPIC: Interesting talk on Python vs. Ruby and how he would like Python to
have just a bit more syntactic flexibility.
http://groups.google.com/group/comp.lang.python/t/9a88c79d4043ba30?hl=en
==============================================================================

== 1 of 11 ==
Date: Wed, Feb 17 2010 4:37 pm
From: Steven D'Aprano


On Thu, 18 Feb 2010 11:46:52 +1300, Lawrence D'Oliveiro wrote:

> In message <hlhdsi$2pn$1@theodyn.ncf.ca>, cjw wrote:
>
>> Aren't lambda forms better described as function?
>
> Is this a function?
>
> lambda : None
>
> What about this?
>
> lambda : sys.stdout.write("hi there!\n")

Of course they are; the first is a function that takes no arguments and
returns None, and the second is a function that takes no arguments,
returns None, and has a side-effect of writing "hi there\n" to stout.

But I imagine you already know that, so I'm not really sure I understand
the point of your (rhetorical?) question.


--
Steven


== 2 of 11 ==
Date: Wed, Feb 17 2010 5:00 pm
From: Jonathan Gardner


On Feb 17, 10:39 am, John Bokma <j...@castleamber.com> wrote:
> Jonathan Gardner <jgard...@jonathangardner.net> writes:
> > Then I looked at a stack trace from a different programming language
> > with lots of anonymous functions. (I believe it was perl.)
>
> > I became enlightened.
>
> If it was Perl [1], I doubt it. Because line numbers are reported, and
> if that doesn't help you, you can annotate anonymous functions with a
> nick name using
>
> local *__ANON__ = 'nice name';
>
> Finding an issue, and not looking for a solution is not called becoming
> enlightened ;-)
>
> ~$ perl -e '
> use Carp;
>
> my $anon = sub { local *__ANON__ = "hello, world"; croak "oops"; };
> $anon->();
> '
>
> oops at -e line 4
>         main::hello, world() called at -e line 5
>
> As you can see, and a line number is generated, and the nice name is
> shown.
>
> If you generate anonymouse functions on the fly based on parameters, you
> can encode this into the nice name, of course.
>
> Sadly, often bold statements about a language are made in ignorance.
>

$ perl -e '$a = sub () {die "it may have been javascript, but"}; $b =
sub () {die "I am pretty sure it was perl"}; $b->()'


== 3 of 11 ==
Date: Wed, Feb 17 2010 5:02 pm
From: Jonathan Gardner


On Feb 17, 12:02 am, Lawrence D'Oliveiro <l...@geek-
central.gen.new_zealand> wrote:
> In message
> <8ca440b2-6094-4b35-80c5-81d000517...@v20g2000prb.googlegroups.com>,
>
> Jonathan Gardner wrote:
> > I used to think anonymous functions (AKA blocks, etc...) would be a
> > nice feature for Python.
>
> > Then I looked at a stack trace from a different programming language
> > with lots of anonymous functions. (I believe it was perl.)
>
> Didn't it have source line numbers in it?
>
> What more do you need?

I don't know, but I tend to find the name of the function I called to
be useful. It's much more memorable than line numbers, particularly
when line numbers keep changing.

I doubt it's just me, though.


== 4 of 11 ==
Date: Wed, Feb 17 2010 5:04 pm
From: Jonathan Gardner


On Feb 17, 12:02 am, Lawrence D'Oliveiro <l...@geek-
central.gen.new_zealand> wrote:
> In message <60b1abce-4381-46ab-91ed-
>
> f2ab2154c...@g19g2000yqe.googlegroups.com>, Andrej Mitrovic wrote:
> > Also, lambda's are expressions, not statements ...
>
> Is such a distinction Pythonic, or not? For example, does Python distinguish
> between functions and procedures?

Not to the programmer, no. Callables are callable, no matter what they
are, and they are all called the same way.

(What the heck is a procedure, anyway? Is this different from a
subroutine, a method, or a block?)


== 5 of 11 ==
Date: Wed, Feb 17 2010 5:06 pm
From: Steven D'Aprano


On Wed, 17 Feb 2010 12:39:30 -0600, John Bokma wrote:

> Jonathan Gardner <jgardner@jonathangardner.net> writes:
>
>> Then I looked at a stack trace from a different programming language
>> with lots of anonymous functions. (I believe it was perl.)
>>
>> I became enlightened.
>
> If it was Perl [1], I doubt it. Because line numbers are reported, and
> if that doesn't help you, you can annotate anonymous functions with a
> nick name using
>
> local *__ANON__ = 'nice name';
[...]
> As you can see, and a line number is generated, and the nice name is
> shown.

Given that it has a nice name, what makes it an anonymous function?

It seems to me that Perl effectively has three ways of creating
functions, one anonymous and two named (even if one syntax for creating a
named function is almost identical to the syntax for creating an
anonymous function). Once you annotate a function with a nickname, it's
no different from giving it a name.

If this is the case, then your answer to "anonymous functions are a PITA"
is "don't use anonymous functions", which exactly the same answer we'd
give here in Python land. The only difference is that Perl provides two
ways of making a named function, and Python only one[1].


[1] Technically, you can make named functions with the new module and a
bit of work, so Python has two ways too.


--
Steven


== 6 of 11 ==
Date: Wed, Feb 17 2010 5:20 pm
From: "Rhodri James"


On Thu, 18 Feb 2010 01:04:00 -0000, Jonathan Gardner
<jgardner@jonathangardner.net> wrote:

> On Feb 17, 12:02 am, Lawrence D'Oliveiro <l...@geek-
> central.gen.new_zealand> wrote:
>> In message <60b1abce-4381-46ab-91ed-
>>
>> f2ab2154c...@g19g2000yqe.googlegroups.com>, Andrej Mitrovic wrote:
>> > Also, lambda's are expressions, not statements ...
>>
>> Is such a distinction Pythonic, or not? For example, does Python
>> distinguish
>> between functions and procedures?
>
> Not to the programmer, no. Callables are callable, no matter what they
> are, and they are all called the same way.
>
> (What the heck is a procedure, anyway? Is this different from a
> subroutine, a method, or a block?)

In classic Pascal, a procedure was distinct from a function in that it had
no return value. The concept doesn't really apply in Python; there are no
procedures in that sense, since if a function terminates without supplying
an explicit return value it returns None.

--
Rhodri James *-* Wildebeeste Herder to the Masses


== 7 of 11 ==
Date: Wed, Feb 17 2010 5:39 pm
From: Steven D'Aprano


On Wed, 17 Feb 2010 17:04:00 -0800, Jonathan Gardner wrote:

> (What the heck is a procedure, anyway? Is this different from a
> subroutine, a method, or a block?)

The name is used in Pascal, which probably means it originated from
Fortran or Algol.

A subroutine is a generic piece of code which can be re-used by some
unspecified mechanism (GOSUB in Basic, by calling it in most other
languages). A function is a subroutine that returns a result, and a
procedure is a subroutine that doesn't return anything (not even None, or
the equivalent thereof) and operates entirely by side-effect.

--
Steven


== 8 of 11 ==
Date: Wed, Feb 17 2010 6:23 pm
From: John Bokma


Steven D'Aprano <steven@REMOVE.THIS.cybersource.com.au> writes:

> On Wed, 17 Feb 2010 12:39:30 -0600, John Bokma wrote:

[..]

>> If it was Perl [1], I doubt it. Because line numbers are reported, and
>> if that doesn't help you, you can annotate anonymous functions with a
>> nick name using
>>
>> local *__ANON__ = 'nice name';
> [...]
>> As you can see, and a line number is generated, and the nice name is
>> shown.
>
> Given that it has a nice name, what makes it an anonymous function?

You can't do

nice name();

It just changes what perl reports.

> If this is the case, then your answer to "anonymous functions are a
> PITA"

I don't think anon functions are in general a
PITA. Like with most things, (I) use them in moderation.

> is "don't use anonymous functions", which exactly the same answer we'd
> give here in Python land. The only difference is that Perl provides two
> ways of making a named function, and Python only one[1].

Note that the local trick doesn't create a named function. There are
other ways of course to create named functions in Perl, e.g.

perl -e '*foo=sub { print "hello, world\n" }; foo();'

Which can be fun:

perl -e '
sub AUTOLOAD {
my $name = our $AUTOLOAD;
*$AUTOLOAD = sub { local $" = ", "; print "$name(@_)\n" };
goto &$AUTOLOAD;
}
foo(40);
bar("hello", "world!");
baz(foo(10));'

output:

main::foo(40)
main::bar(hello, world!)
main::foo(10)
main::baz(1)

NB: calling foo 10 returns 1 (return value of print).

--
John Bokma j3b

Hacking & Hiking in Mexico - http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development


== 9 of 11 ==
Date: Wed, Feb 17 2010 6:27 pm
From: Steve Howell


On Feb 17, 5:39 pm, Steven D'Aprano
<ste...@REMOVE.THIS.cybersource.com.au> wrote:
> On Wed, 17 Feb 2010 17:04:00 -0800, Jonathan Gardner wrote:
> > (What the heck is a procedure, anyway? Is this different from a
> > subroutine, a method, or a block?)
>
> The name is used in Pascal, which probably means it originated from
> Fortran or Algol.
>
> A subroutine is a generic piece of code which can be re-used by some
> unspecified mechanism (GOSUB in Basic, by calling it in most other
> languages). A function is a subroutine that returns a result, and a
> procedure is a subroutine that doesn't return anything (not even None, or
> the equivalent thereof) and operates entirely by side-effect.
>

Those are useful clarifications, but they are not completely
universal.

Some people make the definition of function more restrictive--"if it
has side effects, it is not a function."

Python's definition of a method is also not universal. In some
circles, method is more akin to Steven's definition of a procedure--it
does not necessarily have to be associated with a class.

It's all very confusing, which is why Pythonistas are typically
adamant about clarifying definitions within Python's context, which is
understandable. To the extent that we're all talking about one
programming language, we should use the same terms.

A quick Google search does not turn up an official definition of a
Ruby block, although the term "block" is colloquially used in both
Python and Ruby to refer to a bunch of lines of code executed in a
particular context, like a loop.

Python may not support the broadest notion of anonymous functions, but
it definitely has anonymous blocks. You can write this in Python:

for i in range(10):
print i
print i * i
print i * i * i

Python does not force you to do this:

def do_stuff(i):
print i
print i * i
print i * i * i
for i in range(10):
do_stuff(i)


== 10 of 11 ==
Date: Wed, Feb 17 2010 7:10 pm
From: Steve Howell


On Feb 16, 4:19 pm, Jonathan Gardner <jgard...@jonathangardner.net>
wrote:
> On Feb 16, 11:41 am, Andrej Mitrovic <andrej.mitrov...@gmail.com>
> wrote:
>
>
>
> > On Feb 16, 7:38 pm, Casey Hawthorne <caseyhHAMMER_T...@istar.ca>
> > wrote:
>
> > > Interesting talk on Python vs. Ruby and how he would like Python to
> > > have just a bit more syntactic flexibility.
>
> > >http://blog.extracheese.org/2010/02/python-vs-ruby-a-battle-to-the-de...
> > > --
> > > Regards,
> > > Casey
>
> > Gary's friend Geoffrey Grosenbach says in his blog post (which Gary
> > linked to): "Python has no comparable equivalent to Ruby's do end
> > block. Python lambdas are limited to one line and can't contain
> > statements (for, if, def, etc.). Which leaves me wondering, what's the
> > point?"
>
> > I'm sorry, lambda's do support if's and for's. Also, lambda's are
> > expressions, not statements, but you can pass them around, keep them
> > in a dictionary if you want to. And if you need more than one line of
> > statements, for crying out loud use a def? And who needs those "do-
> > end" blocks anyway, trying to turn Python into Pascal?
>
> I used to think anonymous functions (AKA blocks, etc...) would be a
> nice feature for Python.
>
> Then I looked at a stack trace from a different programming language
> with lots of anonymous functions. (I believe it was perl.)
>
> I became enlightened.

I use Ruby a lot in my day job, and we rarely use blocks are as
anonymous callback functions, which was probably the source of your
pain in other languages.

Often Ruby blocks are just three or four lines of code that are
inlined into a still small function, so as long as the outer function
is still small (which Ruby's blocks help with--they promote
terseness), it's pretty easy to find a buggy function within a
traceback that is not overly big.

It's also possible in Ruby to use quality-promoting techniques like
unit testing, pair programming, deliberateness, etc., to avoid the
need for looking at tracebacks in the first place.

Python is not immune to hard-to-understand tracebacks, since you often
don't often know how a method got itself into the stracktrace in the
first place:

Traceback (most recent call last):
File "foo.py", line 11, in <module>
foo(method)
File "foo.py", line 2, in foo
method()
File "foo.py", line 5, in bar
raise Exception('I am broken!')
Exception: I am broken!

Even though there's no direct lexical reference to bar() in foo(), lo
and behold, foo() ends up calling bar():

def foo(method):
method()

def bar():
raise Exception('I am broken!')

def broken_function_factory():
return bar

method = broken_function_factory()
foo(method)


== 11 of 11 ==
Date: Wed, Feb 17 2010 7:18 pm
From: Carl Banks


On Feb 17, 10:39 am, John Bokma <j...@castleamber.com> wrote:
> Jonathan Gardner <jgard...@jonathangardner.net> writes:
> > Then I looked at a stack trace from a different programming language
> > with lots of anonymous functions. (I believe it was perl.)
>
> > I became enlightened.
>
> If it was Perl [1], I doubt it. Because line numbers are reported

Ok so sonetimes I'm looking at a stack trace and sometimes I can tell
what the bug is just by lookong at the function namess. But if it has
just line numbers I have to dig through my code looking for the line.


> and
> if that doesn't help you, you can annotate anonymous functions with a
> nick name using
>
> local *__ANON__ = 'nice name';
>
> Finding an issue, and not looking for a solution is not called becoming
> enlightened ;-)

The issue is that a stacktrace showing a bunch of nameless line
numbers can be a bad idea, not that Perl might be deficient (and we
already know that in any case), so it's not good to use a lot of
them. Anyway once you annotate an anonymous function, it's no longer
anonymous.


> ~$ perl -e '
> use Carp;
>
> my $anon = sub { local *__ANON__ = "hello, world"; croak "oops"; };
> $anon->();
> '
>
> oops at -e line 4
>         main::hello, world() called at -e line 5
>
> As you can see, and a line number is generated, and the nice name is
> shown.
>
> If you generate anonymouse functions on the fly based on parameters, you
> can encode this into the nice name, of course.
>
> Sadly, often bold statements about a language are made in ignorance.

I don't see what he said was any kind of a bold statement about a
language, arguably it was about the coding style. That Perl allows
annotating functions doesn't mean people do it.


Carl Banks
>
> [1] perl is the program that executes Perl programs ;-).
>
> --
> John Bokma                                                               j3b
>
> Hacking & Hiking in Mexico -  http://johnbokma.com/http://castleamber.com/- Perl & Python Development


==============================================================================
TOPIC: Which mock library do you prefer?
http://groups.google.com/group/comp.lang.python/t/a12daa9de8354ff2?hl=en
==============================================================================

== 1 of 2 ==
Date: Wed, Feb 17 2010 4:49 pm
From: Mark Lawrence


Phlip wrote:
> On Feb 17, 6:26 am, Lacrima <lacrima.ma...@gmail.com> wrote:
>
>> Right, isolation is essential.
>
> Please read my reply: Ben is well intentioned but completely wrong
> here.
>
> Mock abuse will not cure the runtime isolation problem.
>

I believe that Ben is perfectly correct, and that you are talking at
cross purposes because you've missed the significance of his
<quote>
(you later realise)
</quote>
within his post.
Runtime test isolation doesn't enter into from what I can see.
Can you please clarify the situation one way or the other.

TIA.

Mark Lawrence.

== 2 of 2 ==
Date: Wed, Feb 17 2010 5:20 pm
From: Ben Finney


Lacrima <lacrima.maxim@gmail.com> writes:

> Right, isolation [of test cases] is essential. But I can't decide to
> which extent I should propagate isolation.

You used "propagate" in a sense I don't understand there.

> For example, in "Python Testing: Beginner's Guide" by Daniel Arbuckle,
> author suggests that if you do unittesting you should isolate the
> smallest units of code from each other.

I'm not sure what the author means, but I would say that as it stands
that advice is independent of what testing is being done. In all cases:

* Make your code units small, so each one is not doing much and is easy
to understand.

* Make the interface of units at each level as narrow as feasible, so
they're not brittle in the face of changes to the implementation.

> For example, if you have a
> class:
> Class SomeClass(object):
> def method1(self):
> return 5
> def method2(self):
> return self.method1 + 10
>
> According to the book, if you want to test method2, you should isolate
> it from method1 and class instance('self').

I don't really know what that means.

Remember that each test case should not be "test method1". That is far
too broad, and in some cases too narrow. There is no one-to-one mapping
between methods and unit test cases.

Instead, each test case should test one true-or-false assertion about
the behaviour of the code. "When we start with this initial state (the
test fixture), and perform this operation, the resulting state is that".

It makes a lot of sense to name the test case so the assertion being
made *is* its name: not 'test frobnicate' with dozens of assertions, but
one 'test_frobnicate_with_valid_spangulator_returns_true' which makes
that assertion, and extra ones for each distinct assertion.

The failure of a unit test case should indicate *exactly* what has gone
wrong. If you want to make multiple assertions about a code unit, write
multiple test cases for that unit and name the tests accordingly.

This incidentally requires that you test something small enough that
such a true-or-false assertion is meaningful, which leads to
well-designed code with small easily-tested code units. But that's an
emergent property, not a natural law.

> Currently, I don't create mocks of units if they are within the same
> class with the unit under test. If that is not right approach, please,
> explain what are best practices... I am just learning TDD..

In the fixture of the unit test case, create whatever test doubles are
necessary to put your code into the initial state you need for the test
case; then tear all those down whatever the result of the test case.

If you need to create great honking wads of fixtures for any test case,
that is a code smell: your code units are too tightly coupled to
persistent state, and need to be decoupled with narrow interfaces.

The Python 'unittest' module makes this easier by letting you define
fixtures common to many test cases (the 'setUp' and 'tearDown'
interface). My rule of thumb is: if I need to make different fixtures
for some set of test cases, I write a new test case class for those
cases.

--
\ "Following fashion and the status quo is easy. Thinking about |
`\ your users' lives and creating something practical is much |
_o__) harder." —Ryan Singer, 2008-07-09 |
Ben Finney

==============================================================================
TOPIC: How to efficiently extract information from structured text file
http://groups.google.com/group/comp.lang.python/t/bc8840f8a254056b?hl=en
==============================================================================

== 1 of 2 ==
Date: Wed, Feb 17 2010 5:13 pm
From: Jonathan Gardner


On Feb 16, 3:48 pm, Imaginationworks <xiaju...@gmail.com> wrote:
> Hi,
>
> I am trying to read object information from a text file (approx.
> 30,000 lines) with the following format, each line corresponds to a
> line in the text file.  Currently, the whole file was read into a
> string list using readlines(), then use for loop to search the "= {"
> and "};" to determine the Object, SubObject,and SubSubObject. My
> questions are
>
> 1) Is there any efficient method that I can search the whole string
> list to find the location of the tokens(such as '= {' or '};'
>
> 2) Is there any efficient ways to extract the object information you
> may suggest?

Parse it!

Go full-bore with a real parser. You may want to consider one of the
many fine Pythonic implementations of modern parsers, or break out
more traditional parsing tools.

This format is nested, meaning that you can't use regexes to parse
what you want out of it. You're going to need a real, full-bore, no-
holds-barred parser for this.

Don't worry, the road is not easy but the destination is absolutely
worth it.

Once you come to appreciate and understand parsing, you have earned
the right to call yourself a red-belt programmer. To get your black-
belt, you'll need to write your own compiler. Having mastered these
two tasks, there is no problem you cannot tackle.

And once you realize that every program is really a compiler, then you
have truly mastered the Zen of Programming in Any Programming Language
That Will Ever Exist.

With this understanding, you will judge programming language utility
based solely on how hard it is to write a compiler in it, and
complexity based on how hard it is to write a compiler for it. (Notice
there are not a few parsers written in Python, as well as Jython and
PyPy and others written for Python!)


== 2 of 2 ==
Date: Wed, Feb 17 2010 5:38 pm
From: Steven D'Aprano


On Wed, 17 Feb 2010 17:13:23 -0800, Jonathan Gardner wrote:

> And once you realize that every program is really a compiler, then you
> have truly mastered the Zen of Programming in Any Programming Language
> That Will Ever Exist.

In the same way that every tool is really a screwdriver.


--
Steven

==============================================================================
TOPIC: Wrap and intercept function calls
http://groups.google.com/group/comp.lang.python/t/8785a4e8d85dd581?hl=en
==============================================================================

== 1 of 2 ==
Date: Wed, Feb 17 2010 5:44 pm
From: geremy condra


On Wed, Feb 17, 2010 at 11:04 AM, Dan Yamins <dyamins@gmail.com> wrote:
> Really, nobody has any idea about this?   (Sorry to repost.)
>
> On Tue, Feb 16, 2010 at 7:29 PM, Dan Yamins <dyamins@gmail.com> wrote:
>>
>> Hi:
>>
>> I'm wondering what the best way to wrap and modify function calls is.
>> Essentially what I want to achieve is to have a function like this:
>>
>> def Wrap(frame,event,arg):
>>      if event == 'call':
>>         result = PerformCheck(GetArgumentsFromFrame(frame))
>>         if Condition(result):
>>             return result
>>         else:
>>             return [normal function call]
>>
>> called whenever a "call" event is about to occur.
>>
>> When I say "return result" I mean:  return that data object instead of
>> what the function would have returned, and prevent execution of the
>> function.
>>
>> Is there any way to do this using sys.settrace?  Or perhaps something from
>> the bdb or pbd module?
>>
>
> In other words, what I'm looking for is a way to intercept all function
> calls with a "wrapper" --  like one can do using settrace and other
> debugging methods -- but, unlike the debugging methods, have the "wrapping"
> function actually be able to intervene in the stack and, for instance,
> conditionally replace the function call's return with something determined
> in the wrapping function and prevent the function call's execution.   I want
> to be able to do this by setting a single system-wide (or at any rate,
> thread-wide) value, like with settrace, and not have to modify individual
> functions one by one.
>
> Could I, for example, set a settrace function that somehow modifies the
> stack?  Or is there some much better way to do this?  Or, if someone can
> tell me that this can't be done without having to roll my own implementation
> of the Python interpreter, that would be great to know too.
>
> Thanks again,
> Dan
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>

You could drill down through everything in globals() etc, replacing
functions as you went,
but its fragile (there are probably unworkable corner cases), ugly,
and likely to be slow.
What exactly is it you're trying to do?

Geremy Condra


== 2 of 2 ==
Date: Wed, Feb 17 2010 6:42 pm
From: alex23


Terry Reedy <tjre...@udel.edu> wrote:
> Now wrap *every* function you are interested in. Builtin functions are
> no problem; methods of builtin classes cannont be wrapped without
> subclassing.

It's a shame it's not possible to do:

type.__call__ = func_wrap(type.__call__)

Or even:

type.__class__ = NewType

==============================================================================
TOPIC: Draft paper submission deadline is extended: SETP-10, Orlando, USA
http://groups.google.com/group/comp.lang.python/t/b8af1aeb393da22a?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 6:29 pm
From: James Heralds


It would be highly appreciated if you could share this announcement
with your colleagues, students and individuals whose research is in
software engineering, software testing, software quality assurance,
software design and related areas.

Draft paper submission deadline is extended: SETP-10, Orlando, USA

The 2010 International Conference on Software Engineering Theory and
Practice (SETP-10) (website: http://www.PromoteResearch.org) will be
held during 12-14 of July 2010 in Orlando, FL, USA. SETP is an
important event in the areas of Software development, maintenance, and
other areas of software engineering and related topics.

The conference will be held at the same time and location where
several other major international conferences will be taking place.
The conference will be held as part of 2010 multi-conference
(MULTICONF-10). MULTICONF-10 will be held during July 12-14, 2010 in
Orlando, Florida, USA. The primary goal of MULTICONF is to promote
research and developmental activities in computer science, information
technology, control engineering, and related fields. Another goal is
to promote the dissemination of research to a multidisciplinary
audience and to facilitate communication among researchers,
developers, practitioners in different fields. The following
conferences are planned to be organized as part of MULTICONF-10.

• International Conference on Artificial Intelligence and Pattern
Recognition (AIPR-10)
• International Conference on Automation, Robotics and Control
Systems (ARCS-10)
• International Conference on Bioinformatics, Computational Biology,
Genomics and Chemoinformatics (BCBGC-10)
• International Conference on Computer Communications and Networks
(CCN-10)
• International Conference on Enterprise Information Systems and Web
Technologies (EISWT-10)
• International Conference on High Performance Computing Systems
(HPCS-10)
• International Conference on Information Security and Privacy
(ISP-10)
• International Conference on Image and Video Processing and Computer
Vision (IVPCV-10)
• International Conference on Software Engineering Theory and Practice
(SETP-10)
• International Conference on Theoretical and Mathematical Foundations
of Computer Science (TMFCS-10)

MULTICONF-10 will be held at Imperial Swan Hotel and Suites. It is a
full-service resort that puts you in the middle of the fun! Located
1/2 block south of the famed International Drive, the hotel is just
minutes from great entertainment like Walt Disney World® Resort,
Universal Studios and Sea World Orlando. Guests can enjoy free
scheduled transportation to these theme parks, as well as spacious
accommodations, outdoor pools and on-site dining — all situated on 10
tropically landscaped acres. Here, guests can experience a full-
service resort with discount hotel pricing in Orlando.


We invite draft paper submissions. Please see the website
http://www.PromoteResearch.org for more details.

==============================================================================
TOPIC: Traversing through variable-sized lists
http://groups.google.com/group/comp.lang.python/t/6f56c35ab7103a91?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 6:59 pm
From: Andrej Mitrovic


On Feb 17, 11:56 pm, Dave Angel <da...@ieee.org> wrote:
> Andrej Mitrovic wrote:
> > On Feb 17, 8:24 pm, John Posner <jjpos...@optimum.net> wrote:
>
> >> On 2/17/2010 1:10 PM, Andrej Mitrovic wrote:
>
> >> <snip>
>
> > However the values list might have an uneven number of items. I would
> > like to make it as evenly distributed as possible, e.g.:
>
> > values =-2, -1, 0]
> > frames =obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8]
>
> > frames[0].func(values[0])  # func.(values[-2])
> > frames[1].func(values[0])  # func.(values[-2])
> > frames[2].func(values[1])  # func.(values[-2])
> > frames[3].func(values[1])  # func.(values[-1])
> > frames[4].func(values[1])  # func.(values[-1])
> > frames[5].func(values[2])  # func.(values[-1])
> > frames[6].func(values[2])  # func.(values[0])
> > frames[7].func(values[2])  # func.(values[0])
>
> > I'll be even more specific. I have a Minimum and Maximum value that
> > the user enters. The frame.func() function is a "translate" function,
> > it basically moves a frame in the application in one direction or
> > another depending on the argument value. So frame[0].func(2) would
> > move the frame[0] 2 pixels to the right. So what I want is the
> > function to create a smooth transition of all the frames from the
> > Minimum to the Maximum value. If minimum was 0, and maximum was 10,
> > I'd want the first frame moved 0 pixels (it stays in place), the last
> > frame to move 10 pixels, and the frames between are gradually moved
> > from 1 pixels to 9 pixels relative from their positions.
>
> > Perhaps I'm just overcomplicating. I'll have a look at some drawing
> > apps and see how they've implemented drawing straight lines under an
> > angle, I guess that could be called a gradual change of values.
>
> > Thanks for all the suggestions everyone, I'll have a look at the rest
> > shortly.
>
> I think you're overcomplicating.  If you have 27 frames, and you want
> frame 0 to move 0 pixels, and frame 27 to move 10 pixels, then you want
> to move frame[i] by i*10/27.  And since you do the multiply first, the
> fact that Python 2.x division gives you integers isn't a problem.
>
> There are fancier methods for drawing lines (bresenham for example), but
> the main purpose of them is to to avoid multiply and divide, as well as
> floats.  But in Python, an integer multiply is just as fast as an add or
> subtract, so there's no point.
>
> DaveA

Doh! Such a simple solution, just what I was looking for. Thanks!


==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate