Monday, November 7, 2011

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

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

comp.lang.python@googlegroups.com

Today's topics:

* Usefulness of the "not in" operator - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/d09d45e170c26a50?hl=en
* Python lesson please - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/a361946a1ecf9964?hl=en
* Oktest.py 0.10.0 released - a new-style testing library - 1 messages, 1
author
http://groups.google.com/group/comp.lang.python/t/5f69f33d9d6a96e9?hl=en
* Question about 'iterable cursors' - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/996dd8dd5c5e92bf?hl=en
* How to undo a Python setuptools --prefix path blunder - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/8eff68d634e3942b?hl=en
* RSS feed creation? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/d2a3d88db209539f?hl=en

==============================================================================
TOPIC: Usefulness of the "not in" operator
http://groups.google.com/group/comp.lang.python/t/d09d45e170c26a50?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Nov 6 2011 3:23 pm
From: DevPlayer


On Oct 16, 12:05 am, Steven D'Aprano <steve
+comp.lang.pyt...@pearwood.info> wrote:
> On Sat, 15 Oct 2011 15:04:24 -0700, DevPlayer wrote:
> > I thought "x not in y" was later added as syntax sugar for "not x in y"
> > meaning they used the same set of tokens. (Too lazy to check the actual
> > tokens)
Stated in response to OP wanting a seperate token for "not in" verse
"is not".

> Whether the compiler has a special token for "not in" is irrelevant.
I don't know.

> Perhaps it uses one token, or two, or none at all because a
> pre-processor changes "x not in y" to "not x in y". That's
> an implementation detail.
I agree.

> What's important is whether it is valid syntax or not, and how it is
> implemented.
I agree.

> As it turns out, the Python compiler does not distinguish the two forms:
>
> >>> from dis import dis
> >>> dis(compile('x not in y', '', 'single'))
>
>   1           0 LOAD_NAME                0 (x)
>               3 LOAD_NAME                1 (y)
>               6 COMPARE_OP               7 (not in)
>               9 PRINT_EXPR
>              10 LOAD_CONST               0 (None)
>              13 RETURN_VALUE        >>> dis(compile('not x in y', '', 'single'))
>
>   1           0 LOAD_NAME                0 (x)
>               3 LOAD_NAME                1 (y)
>               6 COMPARE_OP               7 (not in)
>               9 PRINT_EXPR
>              10 LOAD_CONST               0 (None)
>              13 RETURN_VALUE

So cool! Thanks for showing how to do that.

I tried to say implementing a seperate method was not efficient.

> Also for what it is worth, "x not in y" goes back to at least Python 1.5,
> and possibly even older. (I don't have any older versions available to
> test.)
So "not in" was added as an alternative (just a long time ago).
I too am glad they added it.

> (2) Instead of writing "True if blah else False", write "bool(blah)".
Good tip! I like.

>
> > class Y(object):
> >     def __contains__(self, x):
> >         for item in y:
> >         if x == y:
> >             return True
> >         return False
>
> You don't have to define a __contains__ method if you just want to test
> each item sequentially. All you need is to obey the sequence protocol and
> define a __getitem__ that works in the conventional way:

Didn't intend to show how to implement __contains__ using "==" and
__not_contains__ "<>" in python but to show that python didn't benefit
from the not_in loop as much as for example assembly language does
it's loop (x86 LOOPE/LOOPZ vs LOOPNZ/LOOPNE).

>
> >>> class Test:
>
> ...     def __init__(self, args):
> ...             self._data = list(args)
> ...     def __getitem__(self, i):
> ...             return self._data[i]
> ...>>> t = Test("abcde")
> >>> "c" in t
> True
> >>> "x" in t
> False
Another new thing for me.

>
> Defining a specialist __contains__ method is only necessary for non-
> sequences, or if you have some fast method for testing whether an item is
> in the object quickly. If all you do is test each element one at a time,
> in numeric order, don't bother writing __contains__.
>
> > And if you wanted "x not in y" to be a different token you'd have to ADD
>
> Tokens are irrelevant. "x not in y" is defined to be the same as "not x
> in y" no matter what.
> You can't define "not in" to do something completely different.
I agree they are not implemented differently.
I agree that they shouldn't be implemented differently.
I disagree they can not be implemented differently. I think they can.
But I see no reason too.

> > class Y(object):
> >     def __not_contained__(self, x):
> >         for item in self:
> >             if x == y:
> >                 return False
> >         return True
>
> > AND with __not_contained__() you'd always have to iterate the entire
> > sequence to make sure even the last item doesn't match.
> > SO with one token "x not in y" you DON'T have to itterate through the
> > entire sequence thus it is more effiecient.
> That's not correct.
> Steven
I tried to prove my point and failded and instead proved (to myself)
you are correct. It is not more efficient. Also I should have used if
<> y: continue to have better tried to make the point but it wouldn't
have mattered. I still would have been wrong.

But I did walk away from this topic with some goodie tips. Thanks
Steven.

==============================================================================
TOPIC: Python lesson please
http://groups.google.com/group/comp.lang.python/t/a361946a1ecf9964?hl=en
==============================================================================

== 1 of 3 ==
Date: Sun, Nov 6 2011 3:27 pm
From: Dave Angel


On 11/06/2011 06:10 PM, gene heskett wrote:
> On Sunday, November 06, 2011 06:07:36 PM Dave Angel did opine:
>
>> On 11/06/2011 01:14 PM, gene heskett wrote:
>>> Greetings experts:
>>>
>>> I just dl'd the duqu driver finder script from a link to NSS on /.,
>>> and fixed enough of the tabs in it to make it run error-free. At
>>> least python isn't having a litter of cows over the indentation now.
>>>
>>> But it also runs instantly on linux.
>>>
>>> This line looks suspect to me:
>>> rootdir = sys.argv[1]
>>>
>>> And I have a suspicion it is null on a linux box.
>>>
>>> How can I fix that best?
>>>
>>> Thanks.
>>>
>>> Cheers, Gene
>>
>> Nothing wrong with that line, assuming the user of the script happened
>> to provide an argument for rootpath. Probably it should be preceded by
>> a a conditional:
>>
>> if len(argv)<2:
>> tell.user.that.she's.missing.the.rootdir.parameter
>> else:
>> rootdir = sys.argv[1]
>> etc.
>>
>> What does the help text show when you run the script with the --help
>> argument?
>
> It has no --help:
> [root@coyote gene]# ./duqu-drivers-detect.py --help
> [root@coyote gene]#
>
> Sorry.
>
> Thanks& Cheers, Gene


So is there any documentation? If not, your first job is to guess what
it's supposed to do, figure out if you care, and then document it. In
the process you'll probably find a few bugs.

First bug is it silently quits when you run it with no arguments. Is
that true? If so, figure out where it quits, since it clearly never
reaches the line you quote.

Actually I'd probably start with the assumption that you might have
messed up the tab expansion somewhere. How did you expand the tabs?
Perhaps by using the Linux expands utility? Or did you do it manually?

--

DaveA


== 2 of 3 ==
Date: Sun, Nov 6 2011 3:54 pm
From: David Riley


On Nov 6, 2011, at 3:34 PM, Cameron Simpson wrote:

> Perhaps more relevantly:
>
> If you have unmangled a lot of tabs, remember that control flow is
> indentation based in python, and you may have broken some logic.
> (For this reason a number of us set our editors to work only in spaces).

I would absolutely check this first. I can't count the number of programs I've screwed up in difficult-to-detect ways because I've converted from tabs to spaces incorrectly. It's how I've finally learned to let a program/script do it for me, because Python is the first language I've used with significant leading whitespace.

- Dave

== 3 of 3 ==
Date: Sun, Nov 6 2011 6:54 pm
From: Steven D'Aprano


On Sun, 06 Nov 2011 13:14:43 -0500, gene heskett wrote:

> I just dl'd the duqu driver finder script from a link to NSS on /., and
> fixed enough of the tabs in it to make it run error-free. At least
> python isn't having a litter of cows over the indentation now.

<raises eyebrow>

Presumably the script should be working. If it is known to be not
working, then you probably need to fix a lot more than just indentation.

If this is "pre-alpha, doesn't even compile" software, then good luck,
you'll need to read the source and understand it to make it work. It's
not sufficient to just get it to a point where you can say "Cool, it
compiles!" by fixing some indentation.

If this is supposed to be working, there's a reason why it's not working
for you. Perhaps you are trying to use it with the wrong version of
Python. Perhaps the download is corrupted. Fix those before mangling
indentation in random ways: start with a fresh, uncorrupted download.
Check that the md5 sum matches that provided by the download site
(assuming they provide one). Find out what version of Python is
supported, and use that.


> This line looks suspect to me:
> rootdir = sys.argv[1]

What makes you think that line is suspect? It looks fine to me.


> And I have a suspicion it is null on a linux box.

This is Python, not bash. Sys arguments are not filled in with "null",
whatever you think "null" is. (The None built-in? The empty string?)

Have you tried giving the script an argument when you call it? If in
doubt, call it with "." (the current directory) as argument.

My wild guess is that you actually need to supply a meaningful directory
path before the script will do anything, and until then, it will silently
fail. Which is terrible design.


> How can I fix that best?

If it's not broken, it doesn't need to be fixed. Don't make assumptions
about what code needs to be fixed based on nothing more than gut feeling.

--
Steven

==============================================================================
TOPIC: Oktest.py 0.10.0 released - a new-style testing library
http://groups.google.com/group/comp.lang.python/t/5f69f33d9d6a96e9?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Nov 6 2011 8:12 pm
From: Makoto Kuwata


Hi,

I released Oktest.py 0.10.0.
http://packages.python.org/Oktest/
http://www.kuwata-lab.com/oktest/

Oktest.py is a new-style testing library for Python.
::

from oktest import ok, NG
ok (x) > 0 # same as assertTrue(x > 0)
ok (s) == 'foo' # same as assertEqual(s, 'foo')
ok (s) != 'foo' # same as assertNotEqual(s, 'foo')
ok (f).raises(ValueError) # same as assertRaises(ValueError, f)
ok (u'foo').is_a(unicode) # same as assertTrue(isinstance(u'foo', unicode))
NG (u'foo').is_a(int) # same as assertTrue(not isinstance(u'foo', int))
ok ('A.txt').is_file() # same as assertTrue(os.path.isfile('A.txt'))
NG ('A.txt').is_dir() # same as assertTrue(not os.path.isdir('A.txt'))

See
http://www.kuwata-lab.com/oktest/oktest-py_users-guide.html
for details.


Changes and Enhancements
------------------------

* [change] 'oktest.spec()' is obsoleted completely.
It will print warning message if you use it.

* [change] 'oktest.helper' module is renamed to 'oktest.util'.
('oktest.helper' is still available for backward compabibility.)

* [enhance] Add 'oktest.main()' which is a replacement of 'oktest.run()'.
Using 'oktest.main()' instead of 'oktest.run()', command options are
available.
ex::

## for example:
$ python test/foobar_test.py -sp -f test='*keyword*'
## is almost same as:
$ python -m oktest test/foobar_test.py -sp -f test='*keyword*'

* [enhance] Add 'oktest.fail(message)' which is same as
'unittest.fail(message)'.
ex::

from oktest import fail
fail("not impelmented yet") # will raise AssertionError

* [enhance] (Experimental) Add '@todo' decorator which is equivarent to
'@unittest.expectedFailure'.
ex::

from oktest import ok, test, todo

def add(x, y):
return 0 # not implemented yet!

class AddTest(unittest.TestCase):
@test("returns sum of arguments.")
@todo # equivarent to @unittest.expectedFailure
def _(self):
ok (10, 20) == 30 ## will be failed expectedly
## (because not implemented yet)

Expected failure of assertion is reported as '[TODO]', not '[Failed]'.

* [enhance] (Experimental) Test context supported.
It helps you to describe specification in structured style.
ex::

from oktest import ok, test
from oktest.context import subject, situation

class SampleTestCase(unittest.TestCase):
SUBJECT = "class 'Sample'"

with subject("method1()"):

with situation("when condition:"):

@test("spec1")
def _(self):
...

@test("spec2")
def _(self):
...

with situation("else:"):

@test("spec3")
def _(self):
...

Output exmple::

$ python test/example_test.py
* class 'Sample'
+ method1()
+ when condition:
- [ok] spec1
- [ok] spec2
+ else:
- [ok] spec3
## total:3, passed:3, failed:0, error:0, skipped:0 (elapsed 0.000)


--
regards,
makoto kuwata

==============================================================================
TOPIC: Question about 'iterable cursors'
http://groups.google.com/group/comp.lang.python/t/996dd8dd5c5e92bf?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Nov 6 2011 10:04 pm
From: John Nagle


On 11/6/2011 12:04 PM, Dennis Lee Bieber wrote:
> On Sun, 6 Nov 2011 11:39:56 +0200, "Frank Millman"<frank@chagford.com>
> declaimed the following in gmane.comp.python.general:
>
>>
>> So my analysis of the problem is correct, but my solution is wrong.
>>
>> Instead of executing fetchall() and returning the connection, I should
>> retain the connection until I have exhausted the cursor.
>>
>> That makes a lot of sense.
>>
> Especially if all you are processing are read-only activities.
>
> If you have a connection/cursor doing write operations, you may not
> be able to commit those writes until all reading cursors have closed.
> (Read the documentation on the SQLite3 locking system -- though the
> newest version has added a second type of locking which may complicate
> the matter. The original/normal scheme has potential readers "outside"
> SQLite3, active readers "inside" SQLite3 -- when an active reader cursor
> advances to a pending write, it blocks all the potential readers from
> entering, but is itself blocked until all other active readers have
> exited)

Right. The scarce resource is database locks, not connections.
Especially with SQLite, which has, by necessity, a rather brutal
locking strategy.

Realize that SQLite is not a high-performance multi-user database.
You use SQLite to store your browser preferences, not your customer
database.

If you're doing enough transactions from multiple processes that
performance is an issue, you need to move up to MySQL or Postgres.
If almost all transactions are SELECTs, performance may not be
too bad, but if there are INSERT and UPDATE transactions on the
same table, performance will be awful.

John Nagle

==============================================================================
TOPIC: How to undo a Python setuptools --prefix path blunder
http://groups.google.com/group/comp.lang.python/t/8eff68d634e3942b?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Nov 6 2011 10:50 pm
From: Matej Cepl


Dne 6.11.2011 14:18, Kev napsal(a):
> Again the wrong path is being used to create the symbolic link to
> where virtualenv is installed:

http://packages.python.org/distribute/easy_install.html#administrator-installation
for list of additional configuration files which might go wrong (namely
*.pth and distutils.cfg).

Is that it?

Matěj

==============================================================================
TOPIC: RSS feed creation?
http://groups.google.com/group/comp.lang.python/t/d2a3d88db209539f?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Nov 6 2011 11:22 pm
From: Stefan Behnel


Dan Stromberg, 06.11.2011 21:00:
> Is there an opensource Python tool for creating RSS feeds, that doesn't
> require large dependencies?
>
> I found feedformatter.py on pypi, but it seems a little old, and its sole
> automated test gives a traceback.
>
> Is there a better starting point?
>
> (I'd of course prefer something that'll run on 3.x and 2.x, but will settle
> for either)

I'd just go with ElementTree and builder.py.

http://effbot.org/zone/element-builder.htm

http://effbot.python-hosting.com/file/stuff/sandbox/elementlib/builder.py

Building an RSS-API on top of that is so trivial that it's not worth any
further dependencies anyway. Not sure if this version of builder.py runs in
Py3, but it certainly won't be hard to fix even if it doesn't currently.

Stefan

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

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