Saturday, April 17, 2010

comp.lang.python - 26 new messages in 12 topics - digest

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

comp.lang.python@googlegroups.com

Today's topics:

* Striving for PEP-8 compliance - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/08f3e64e10fdf47e?hl=en
* An open source AI research project - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/6d9faecf3875aadf?hl=en
* Reactive programming in Python ? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/4b8b621985163c1a?hl=en
* extract substring by regex from a text file - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/020c5160119ab499?hl=en
* Incorrect scope of list comprehension variables - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/2b64b9a9069a324f?hl=en
* class instance customization - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/7fbdeb0c4d8af5c4?hl=en
* cross-platform coloured text in terminal - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/1c1cb43fa8d7a8ac?hl=en
* Creating a standalone application - 2 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/c7afc0febb46bcdc?hl=en
* when should I explicitly close a file? - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/af8041d4cf076178?hl=en
* Calling a class method - 7 messages, 5 authors
http://groups.google.com/group/comp.lang.python/t/ef214fbc70eb57fc?hl=en
* Can someone please make it more pythonic or better? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/9d9412b8cb6d20c9?hl=en
* How to run program in Linux - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/016d98fe9ae9a991?hl=en

==============================================================================
TOPIC: Striving for PEP-8 compliance
http://groups.google.com/group/comp.lang.python/t/08f3e64e10fdf47e?hl=en
==============================================================================

== 1 of 2 ==
Date: Fri, Apr 16 2010 11:20 pm
From: Gregory Ewing


Steven D'Aprano wrote:
> On Wed, 14 Apr 2010 22:10:28 +0200, Hans Mulder wrote:
>
>
>>>Anybody who invents another brace-delimited language should be beaten.
>>>You always end up with a big problem trying to make sure the braces are
>>>consistent with the program logic.
>>
>>Anybody who invents another programming language should be beaten. You
>>always end up with a big problem trying to make sure the program logic
>>is consistent with the customers's needs :-(
>
>
> Anyone who invents another program should be beaten. You always end up
> with a big problem trying to make sure the program logic is consistent
> with what the customer thinks they need.

Anyone who takes on new customers should be beaten. You always end up
with a big problem trying to make sure that what the customer thinks
they need is what they actually need.

--
Greg

== 2 of 2 ==
Date: Sat, Apr 17 2010 5:31 am
From: Lie Ryan


On 04/17/10 16:20, Gregory Ewing wrote:
> Steven D'Aprano wrote:
>> On Wed, 14 Apr 2010 22:10:28 +0200, Hans Mulder wrote:
>>
>>
>>>> Anybody who invents another brace-delimited language should be beaten.
>>>> You always end up with a big problem trying to make sure the braces are
>>>> consistent with the program logic.
>>>
>>> Anybody who invents another programming language should be beaten. You
>>> always end up with a big problem trying to make sure the program logic
>>> is consistent with the customers's needs :-(
>>
>>
>> Anyone who invents another program should be beaten. You always end up
>> with a big problem trying to make sure the program logic is consistent
>> with what the customer thinks they need.
>
> Anyone who takes on new customers should be beaten. You always end up
> with a big problem trying to make sure that what the customer thinks
> they need is what they actually need.

Anyone who makes another joke about anyone who need to be beaten needs
to be beaten. You always end up with a big problem with angry bruised
people wondering why they get beaten up.

==============================================================================
TOPIC: An open source AI research project
http://groups.google.com/group/comp.lang.python/t/6d9faecf3875aadf?hl=en
==============================================================================

== 1 of 3 ==
Date: Sat, Apr 17 2010 1:03 am
From: David Zhang


Hello!

I have started an open source project to develop human-level
Artificial Intelligence, using Python and Java as programming
language, OpenCog and OpenWonderland as basement. If you are
interested in this,or want to know more, please feel free to give me a
reply.

Thanks!

David Zhang


== 2 of 3 ==
Date: Sat, Apr 17 2010 7:13 am
From: Simon Brunning


On 17 April 2010 09:03, David Zhang <david290@gmail.com> wrote:
> I have started an open source project to develop human-level
> Artificial Intelligence...

Have you people never seen Terminator? Sheesh.

--
Cheers,
Simon B.


== 3 of 3 ==
Date: Sat, Apr 17 2010 7:21 am
From: Lie Ryan


On 04/18/10 00:13, Simon Brunning wrote:
> On 17 April 2010 09:03, David Zhang <david290@gmail.com> wrote:
>> I have started an open source project to develop human-level
>> Artificial Intelligence...
>
> Have you people never seen Terminator? Sheesh.

Ssshhh, you're disclosing our top-secret plan...

==============================================================================
TOPIC: Reactive programming in Python ?
http://groups.google.com/group/comp.lang.python/t/4b8b621985163c1a?hl=en
==============================================================================

== 1 of 1 ==
Date: Sat, Apr 17 2010 1:13 am
From: pca


On Apr 17, 8:09 am, Stefan Behnel <stefan...@behnel.de> wrote:
> pca, 16.04.2010 22:02:
>
> > On Apr 16, 8:28 pm, Stefan Behnel wrote:
> >> pca, 16.04.2010 17:18:
>
> >>> In fact, I have seeded an open-source project, Yoopf, that enables
> >>> programming by formula within Python, with the goal of dramatically
> >>> accelerating the development of the model view in the MVC model.
>
> >> Looks like the example on the main page would work better with the "any"
> >> builtin than with the "sum" builtin.
>
> > I'm not sure what you mean.  The example formula in the main page of
> >http://www.yoopf.orgcalculates the total amount of an order as the
> > sum of the amount of each order line: why the 'any' ?
>
> I guess I misinterpreted the phrase "only when one of its order line has
> been added or deleted" as meaning that a change to any of the amounts would
> trigger an event. It wasn't clear to me that the example actually presented
> a calculation that would be evaluated based on that event.
>
> You might want to give potential users a better idea of what this tool
> does. Neither your announcement nor the homepage made that clear to me.
>
> Stefan

Thanks for the feedback, Stefan. I have rephrased the sentence as
follows. Is that more clear ?

"For example, this formula is fed to the library to define the total
amount of each Order object as the sum of the amount of its order
line:

"Order.amount = sum(Order.order_lines.amount)

"At the end of a transaction, the formula calculator is run : it will
calculate the formula only for the Order objects that need
recalculation (e.g because one of its order line has been added or
deleted, or the amount of a line has been changed).

Thanks.
Pierre C.

==============================================================================
TOPIC: extract substring by regex from a text file
http://groups.google.com/group/comp.lang.python/t/020c5160119ab499?hl=en
==============================================================================

== 1 of 3 ==
Date: Sat, Apr 17 2010 1:19 am
From: Alessio


On Apr 15, 3:25 pm, Neil Cerutti <ne...@norwich.edu> wrote:
> On 2010-04-15, Alessio <alessio...@gmail.com> wrote:
>
> > Hi,
>
> > I'm facing the problem in the subject:
> > - I have a text file that I need to parse for producing a specifical
Thank you, I forgot to say that I already solved.
I used readlines() to read my text file, then with a for cicle I
extract line by line the substrings I need by regular expressions
(re.findall())

ciao


> > string (Json like) extracting some information (substring) in it;
> > - I created regural expressions capable to locate these substrings in
> > my txt file;
>
> > now I don't know how to continue. What is the best way to locate some
> > string in a file and output them (with print command or in another
> > file)?
>
> grep
>
> Or: show your work.
>
> --
> Neil Cerutti

== 2 of 3 ==
Date: Sat, Apr 17 2010 1:58 am
From: Stefan Behnel


Alessio, 17.04.2010 10:19:
> I used readlines() to read my text file, then with a for cicle I
> extract line by line the substrings I need by regular expressions
> (re.findall())

Note that it's usually more efficient to just run the for-loop over the
file object, rather than using readlines() first. The latter will read all
lines into a big list in memory before doing any further processing,
whereas the plain for-loop will read line by line and let the loop body act
on each line immediately.

Stefan

== 3 of 3 ==
Date: Sat, Apr 17 2010 2:05 am
From: Peter Otten <__peter__@web.de>


Alessio wrote:

> I used readlines() to read my text file, then with a for cicle I
> extract line by line the substrings I need by regular expressions

Just in case you didn't know:

for line in instream:
...

looks better, uses less memory, and may be a tad faster than

for line in instream.readlines():
...

Peter


==============================================================================
TOPIC: Incorrect scope of list comprehension variables
http://groups.google.com/group/comp.lang.python/t/2b64b9a9069a324f?hl=en
==============================================================================

== 1 of 2 ==
Date: Sat, Apr 17 2010 2:15 am
From: Dave Angel


Steven D'Aprano wrote:
> On Fri, 16 Apr 2010 08:48:03 -0700, Aahz wrote:
>
>
>> In article <4bb92850$0$8827$c3e8da3@news.astraweb.com>, Steven D'Aprano
>> <steve@REMOVE-THIS-cybersource.com.au> wrote:
>>
>>> Nevertheless, it is a common intuition that the list comp variable
>>> should *not* be exposed outside of the list comp, and that the for-loop
>>> variable should. Perhaps it makes no sense, but it is very common --
>>> I've never heard of anyone being surprised that the for-loop variable is
>>> exposed, but I've seen many people surprised by the fact that list-comps
>>> do expose their loop variable.
>>>
>> I've definitely seen people surprised by the for-loop behavior.
>>
>
> What programming languages were they used to (if any)?
>
> I don't know of any language that creates a new scope for loop variables,
> but perhaps that's just my ignorance...
>
>
>
It's not clear whether a language like C or C++ has "loop variables."
It just has variables with varying scope depending on where they're
declared. And you can add extra braces with the sole purpose being to
introduce new variable scoping.

But two things that changed as C evolved were where you could introduce
new variables, and the lifetime of variables introduced in the loop
control structure, rather than inside the braces. The first change was
in C++ from the start, but I think the second change was also an
evolution in C++.

1) In original C, all declarations in a given scope had to occur before
any executable code began. For example, the following was illegal:
int a=12, b=42;
myfunc(a, b);
int c = 9; /* illegal */

2) In original C, and I think in C++, the lifetime of i lasted long
after the loop ended.
for (int i=0; i< limit; ++i)
{
z += i;
}
i is still valid after this curly brace

In C99, and at least in later C++, the scope of i ends with the curly,
as though there were another invisible pair of braces:
{
for (int i=0; i< limit; ++i)
{
z += i;
}}
i is no longer valid here

Because C and C++ have explicit declarations, people who need the loop
variable after the loop is done can simply declare the loop variable
before the for statement.

DaveA

== 2 of 2 ==
Date: Sat, Apr 17 2010 3:05 am
From: Alain Ketterlin


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

> On Fri, 16 Apr 2010 08:48:03 -0700, Aahz wrote:
>
>>>Nevertheless, it is a common intuition that the list comp variable
>>>should *not* be exposed outside of the list comp, and that the for-loop
>>>variable should. Perhaps it makes no sense, but it is very common --
>>>I've never heard of anyone being surprised that the for-loop variable is
>>>exposed, but I've seen many people surprised by the fact that list-comps
>>>do expose their loop variable.
>>
>> I've definitely seen people surprised by the for-loop behavior.
>
> What programming languages were they used to (if any)?
>
> I don't know of any language that creates a new scope for loop variables,
> but perhaps that's just my ignorance...

I think Pascal and Modula-2 do this, Fortran does this, as well as Ada.
I'm sure derivatives of Ada like Oracle's PL/SQL also enforce this. And
of course C/C++/Java if the programmer wants it that way. Actually I
think C was the first to consider "for" as some kind of syntactic sugar
for "while" (thus blurring the notion of a for-loop forever). Python's
for is really a member of the for-each family.

May I add that having strict for-loop iterators is a good thing, at
least in languages like C/C++/Fortran/etc. Optimizing compilers usually
spend some time detecting so-called "induction variables" when they're
not given: it helps simplifying loop bodies, it reduces register
pressure, and changes many array accesses into pointer increments, among
other things.

-- Alain.

==============================================================================
TOPIC: class instance customization
http://groups.google.com/group/comp.lang.python/t/7fbdeb0c4d8af5c4?hl=en
==============================================================================

== 1 of 1 ==
Date: Sat, Apr 17 2010 2:09 am
From: Alexander


Hi, list.

I've some nontrivial class implementation MyClass and its instance my:

my = MyClass(args)

MyClass uses in internals some variable which is not defined in MyClass
itself. I want to extend instance of MyClass at runtime defining this
variable and making new instance. It is like a class inheritance in a
static way

class MyNewClass(MyClass):
def __init__(s, a):
s._variable = a

but this doesn't give me ability to make inheritance at runtime of the
single parent intance. Finaly this should look like this

my = MyClass(args)

a1 = my.new(1)
a2 = my.new(2)

and e.t.c. Is it possible to release this interface in python?

==============================================================================
TOPIC: cross-platform coloured text in terminal
http://groups.google.com/group/comp.lang.python/t/1c1cb43fa8d7a8ac?hl=en
==============================================================================

== 1 of 1 ==
Date: Sat, Apr 17 2010 3:52 am
From: Jonathan Hartley


On Apr 16, 5:59 pm, Lie Ryan <lie.1...@gmail.com> wrote:
> On 04/16/10 19:28, Jonathan Hartley wrote:
>
> > I'm playing with ideas of what API to expose. My favourite one is to
> > simply embed ANSI codes in the stream to be printed. Then this will
> > work as-is on Mac and *nix. To make it work on Windows, printing could
> > be done to a file0-like object which wraps stdout:
>
> The problem with that is you're simply reinventing ANSI.SYS device driver.
>
> An alternative API is you could override .__add__(), like so (completely
> untested):
>
> class Color(object):
>    def __init__(self, color):
>        self.color =  map_the_color(color)
>        self.string = ""
>    def __add__(self, string):
>        self.string += string
>        return self
>    def __str__(self):
>        if terminal_can_do_ansi_color:
>            return ansicolorescape(self.string, self.color)
>        elif windows:
>            syscalltocolor(self.color)
>            print self.string
>            syscalltocolor(reset the color)
>            return ""
>
> GREEN = Color('green')
> print GREEN + "Great" + "Good"
>
> you can even go a bit further and allow chained calls (again, completely
> untested, but you get the idea):
>
> class Color(object):
>    def __init__(self, color):
>        self.color =  map_the_color(color)
>        self.stack = []
>    def __add__(self, string):
>        if isinstance(string, Color):
>            # not a string, chain the calls
>            self.stack.append((string.color, []]))
>        else:
>            # a string,
>            self.stack[-1][1].append(string)
>        return self
>    def __radd__(self, string):
>        self.stack.append([self.default, string])
>        return self
>
>    def __str__(self):
>        if ansi_capable:
>            return colorescape(format, string)
>        elif windows:
>            for format, string in self.stack:
>                syscalltocolor(color)
>                print string
>                return ""
>
> GREEN = Color('green')
> RED = Color('red')
>
> print "Fairly" + GREEN + "Great" + RED + "Poor"
>
> or something like that, and you will have an API that works
> transparently on all platforms. The downside is that you cannot call
> str(GREEN + "foo") on windows.

Hey Lie,

Thanks heaps for the reply!

>> The problem with that is you're simply reinventing ANSI.SYS device driver.

I don't see that as a problem - in fact I think it's exactly my
goal! :-)

The difference is that the ANSI driver requires installation and a
reboot on the end-user's computer, which is a fiddly and intrusive
thing for a Python developer to achieve. Whereas doing the same job in
a Python module is easy to use for the Python developer - they just
import the module, maybe call an 'init()' function, and then the ANSI
functionality works on all platforms.

Your ideas about generating and chaining the ANSI code strings are
great. I worry though, about intermingling the code that generates
ANSI escape sequences with the code which makes them work on Windows.
The problem is that then, only applications which use your ANSI-
generation library will work on Windows. Whereas if these two things
are kept separate, then applications which use any other ANSI-
generation techniques, such as using 'termcolor', or manaully printing
raw ANSI sequences, these can also all work on Windows too, simply by
adding an import and an 'init()' call to the start of the application.

Am I making sense? Many thanks for your thoughts.

Jonathan

==============================================================================
TOPIC: Creating a standalone application
http://groups.google.com/group/comp.lang.python/t/c7afc0febb46bcdc?hl=en
==============================================================================

== 1 of 2 ==
Date: Sat, Apr 17 2010 4:20 am
From: Lawrence D'Oliveiro


In message <fbdf4a20-1fe2-4c23-9ee2-
c6e739362aa1@12g2000yqi.googlegroups.com>, Jonathan Hartley wrote:

> On Apr 13, 10:42�pm, Lawrence D'Oliveiro
> <ldo@geek-central.gen.new_zealand> wrote:
>
>> In message <kZ4xn.868$I8....@news.indigo.ie>, Luis Quesada wrote:
>>
>> > I am getting an "expected string without null bytes" error when using
>> > cxfreeze for creating a standalone application (in Linux-Ubuntu).
>>
>> Why bother? Every decent Linux system will have Python available. Why not
>> just distribute it as a script?
>
> Anything other than a trivial script will have dependencies. These
> might be other Python packages, C-extensions, and other libraries.
> What if your program runs on a version of Python other than the one
> installed on the client's Linux system?

Let the distro maintainers worry about that. They will package your code up
in the appropriate form, so that the system package manager will
automatically ensure that the right dependencies are present. Problem
solved, no need to keep reinventing the wheel.


== 2 of 2 ==
Date: Sat, Apr 17 2010 4:21 am
From: Lawrence D'Oliveiro


In message <4BC4EC17.3040605@4c.ucc.ie>, Luis Quesada wrote:

> Lawrence D'Oliveiro wrote:
>
>> In message <kZ4xn.868$I8.457@news.indigo.ie>, Luis Quesada wrote:
>>
>>> I am getting an "expected string without null bytes" error when using
>>> cxfreeze for creating a standalone application (in Linux-Ubuntu).
>>
>> Why bother? Every decent Linux system will have Python available. Why not
>> just distribute it as a script?
>
> Well every decent Linux system will have Java available too ...

Questionable. Java doesn't seem to be of much importance in the mass market,
it seems to be primarily for corporate use.

==============================================================================
TOPIC: when should I explicitly close a file?
http://groups.google.com/group/comp.lang.python/t/af8041d4cf076178?hl=en
==============================================================================

== 1 of 2 ==
Date: Sat, Apr 17 2010 4:23 am
From: Lawrence D'Oliveiro


In message
<d48b70da-5384-4dc6-9527-46c6b735ccc0@r1g2000yqb.googlegroups.com>, gelonida
wrote:

> I've been told, that following code snippet is not good.
>
> open("myfile","w").write(astring) ...

I do that for reads, but never for writes.

For writes, you want to give a chance for write errors to raise an exception
and alert the user, instead of failing silently, to avoid inadvertent data
loss. Hence the explicit close.


== 2 of 2 ==
Date: Sat, Apr 17 2010 5:33 am
From: Lie Ryan


On 04/17/10 21:23, Lawrence D'Oliveiro wrote:
> In message
> <d48b70da-5384-4dc6-9527-46c6b735ccc0@r1g2000yqb.googlegroups.com>, gelonida
> wrote:
>
>> I've been told, that following code snippet is not good.
>>
>> open("myfile","w").write(astring) ...
>
> I do that for reads, but never for writes.
>
> For writes, you want to give a chance for write errors to raise an exception
> and alert the user, instead of failing silently, to avoid inadvertent data
> loss. Hence the explicit close.

In short, in case of doubt, just be explicit.

Since in python nothing is guaranteed about implicit file close, you
must always explicitly close it.

==============================================================================
TOPIC: Calling a class method
http://groups.google.com/group/comp.lang.python/t/ef214fbc70eb57fc?hl=en
==============================================================================

== 1 of 7 ==
Date: Sat, Apr 17 2010 6:09 am
From: vsoler


I have the following script:

class TTT(object):
def duplica(self):
self.data *= 2
def __init__(self, data):
self.data = data
TTT.duplica(self.data)
def __str__(self):
return str(self.data)

print
obj=TTT(7)
print obj

And I want 14 printed (twice 7)

I got the following error:
TypeError: unbound method duplica() must be called with TTT instance
as first argument (got int instance instead)

What am I doing wrong?


== 2 of 7 ==
Date: Sat, Apr 17 2010 6:44 am
From: Andreas Waldenburger


On Sat, 17 Apr 2010 06:09:21 -0700 (PDT) vsoler
<vicente.soler@gmail.com> wrote:

> I got the following error:
> TypeError: unbound method duplica() must be called with TTT instance
> as first argument (got int instance instead)
>
> What am I doing wrong?

Not reading the error message.

You need to create a TTT instance and call your method from that:

inst = TTT()
inst.duplica(7)


I notice you ask a lot of very basic beginner questions. While there
is nothing wrong with being a beginner and asking questions, I think you
should read more introductory material and tutorials. Concerning
classes, pick one of the following that you like:

http://www.google.com/search?ie=UTF-8&q=python%20classes%20introduction
(Yes I am teasing you a bit ;) )

Also, maybe you'd like to post to the tutor list[1], which is (to my
understanding) intended for just this kind of question.

[1]: http://mail.python.org/mailman/listinfo/tutor

best
/W


--
INVALID? DE!

== 3 of 7 ==
Date: Sat, Apr 17 2010 6:52 am
From: Andreas Waldenburger


On Sat, 17 Apr 2010 06:09:21 -0700 (PDT) vsoler
<vicente.soler@gmail.com> wrote:

> [snip actual question]

Oh and a note on vocabulary: A "class method" is a somewhat advanced
topic and quite probably not what you want here. They are not used very
often.

What I proposed in the other post was an "instance method", which is
usually what one means by the bare word "method". I think you should
familiarize yourself with this concept (that is, just plain Python
object oriented programming with classes and instances), before
delving into more arcane stuff such as class methods.

/W

--
INVALID? DE!

== 4 of 7 ==
Date: Sat, Apr 17 2010 7:06 am
From: Andreas Waldenburger


On Sat, 17 Apr 2010 15:44:56 +0200 Andreas Waldenburger
<usenot@geekmail.INVALID> wrote:

> On Sat, 17 Apr 2010 06:09:21 -0700 (PDT) vsoler
> <vicente.soler@gmail.com> wrote:
>
> > I got the following error:
> > TypeError: unbound method duplica() must be called with TTT instance
> > as first argument (got int instance instead)
> >
> > What am I doing wrong?
>
> Not reading the error message.
>
> [snip rest of my response]
>

No wait. I misread your code. Sorry.

There are two problems with this line:

TTT.duplica(self.data)

It should read

self.duplica()

Then it should work.

It may be a nice exercise for you to work out why the code needs to be
changed like that. On top of that, perhaps you'd like to think about
why you thought it should be "TTT.duplica(self.data)". Comparing that
to the correct way should be very beneficial to you understanding of
the matter. If you like you can post your thoughts here to verify them.

All my comments about reading tutorials and posting to python-tutor
still apply, however.

[Sidenote: What's that lone print statement above "obj=TTT(7)"
supposed to do?]

/W

--
INVALID? DE!

== 5 of 7 ==
Date: Sat, Apr 17 2010 7:16 am
From: Steven D'Aprano


On Sat, 17 Apr 2010 15:44:56 +0200, Andreas Waldenburger wrote:

> On Sat, 17 Apr 2010 06:09:21 -0700 (PDT) vsoler
> <vicente.soler@gmail.com> wrote:
>
>> I got the following error:
>> TypeError: unbound method duplica() must be called with TTT instance as
>> first argument (got int instance instead)
>>
>> What am I doing wrong?
>
> Not reading the error message.
>
> You need to create a TTT instance and call your method from that:
>
> inst = TTT()
> inst.duplica(7)


He already has a TTT instance. Since he's calling the TTT.duplica method
from another TTT method, the easiest way (and the most Pythonic, and the
most sensible, is to do this:

self.duplica(7)

Calling duplica from the class as TTT.duplica will work, if he does:

TTT.duplica(self, 7)

but why would you want to?

--
Steven


== 6 of 7 ==
Date: Sat, Apr 17 2010 7:26 am
From: Walter Brameld IV


vsoler wrote:
> I have the following script:
>
> class TTT(object):
> def duplica(self):
> self.data *= 2
> def __init__(self, data):
> self.data = data
> TTT.duplica(self.data)
> def __str__(self):
> return str(self.data)
>
> print
> obj=TTT(7)
> print obj
>
> And I want 14 printed (twice 7)
>
> I got the following error:
> TypeError: unbound method duplica() must be called with TTT instance
> as first argument (got int instance instead)
>
> What am I doing wrong?

duplica() takes a 'self' parameter (a TTT instance), but you're calling
it with self.data (an int instance). Change this line:

TTT.duplica(self.data)

to this:

TTT.duplica(self)

and it will do what you want.


== 7 of 7 ==
Date: Sat, Apr 17 2010 7:26 am
From: Walter Brameld IV


vsoler wrote:
> I have the following script:
>
> class TTT(object):
> def duplica(self):
> self.data *= 2
> def __init__(self, data):
> self.data = data
> TTT.duplica(self.data)
> def __str__(self):
> return str(self.data)
>
> print
> obj=TTT(7)
> print obj
>
> And I want 14 printed (twice 7)
>
> I got the following error:
> TypeError: unbound method duplica() must be called with TTT instance
> as first argument (got int instance instead)
>
> What am I doing wrong?

duplica() takes a 'self' parameter (a TTT instance), but you're calling
it with self.data (an int instance). Change this line:

TTT.duplica(self.data)

to this:

TTT.duplica(self)

and it will do what you want.

==============================================================================
TOPIC: Can someone please make it more pythonic or better?
http://groups.google.com/group/comp.lang.python/t/9d9412b8cb6d20c9?hl=en
==============================================================================

== 1 of 1 ==
Date: Sat, Apr 17 2010 6:30 am
From: Oltmans


Greetings Python superstars,

I've a directory structure like following

tests /
__init__.py
testfile.py

testfile.py contains following code

import unittest

class Calculator(unittest.TestCase):
def test_add(self):
print 'just add'
def test_divide(self):
print 'diviide'
def test_multiply(self):
print 'mul'


class Car(unittest.TestCase):
def test_start(self):
print 'start'
def test_move_right(self):
print 'move right'
def test_move_left(self):
print 'move left'
def test_stop(self):
print 'stop'


Now give the following user-input I want to get all test-names.
user-input = tests.testfile (get all test-names from all
unittest.TestCase derived classes in test.testfile)
user-input = tests.testfile.Car (get all test-names from the Car
class)
user-input = tests.testfile.Cacr.test_stop

and I'm doing it this the following way and I really think there has
to be more readable, more pythonic and more possibly short way to do
it

import unittest
import sys
import inspect

def get_test_names(full_name,module):
name = full_name.split('.')
loader = unittest.TestLoader()
if len(name) == 4:
return full_name
elif len(name) == 3:
exec "from %s.%s import %s" %(module,name[1],name[2])
return loader.getTestCaseNames(eval(name[2]))
elif len(name) == 2:
exec 'from %s import %s' % (module,name[1])
tests = []
for _name, obj in inspect.getmembers(sys.modules[full_name]):
if inspect.isclass(obj) and
issubclass(obj,unittest.TestCase):
exec "from %s.%s import %s" %
(module,name[1],obj.__name__)
tests.append(loader.getTestCaseNames(obj))
return tests

if __name__ == "__main__":
input = "tests.testfile"
module = input.split('.')[0]
_tests = get_test_names(input,module)
print _tests


So guys, can you kindly point me to a more Pythonic, more readable and
possible more short way to acheive this? I will really appreciate any
help. Many thanks in advance.

Best regards,
Oltmans


==============================================================================
TOPIC: How to run program in Linux
http://groups.google.com/group/comp.lang.python/t/016d98fe9ae9a991?hl=en
==============================================================================

== 1 of 1 ==
Date: Sat, Apr 17 2010 6:53 am
From: Jim Byrnes


Dave Angel wrote:
> Jim Byrnes wrote:
>> Dave Angel wrote:
>>> Jim Byrnes wrote:
>>>> <div class="moz-text-flowed" style="font-family: -moz-fixed">I am just
>>>> learning Python and am new to Linux so I am probably doing something
>>>> to trip myself up. I am trying to run an example GUI program that
>>>> fetches a record from a database. All the files are in the same folder.
>>>>
>>>> The program runs but its results vary depending on how I started it.
>>>> If I run it from the terminal or Idle, I enter a key and the program
>>>> fetches the proper record. If I run it from Nautilis or a panel
>>>> launcher, I enter the proper key and I get an error message saying the
>>>> key does not exist.
>>>>
>>>> I am assuming that I am having path issues but don't know how to
>>>> correct it.
>>>>
>>>> Thamks, Jim
>>>>
>>> Presumably you're also new to mailing lists.
>>
>> Not really.
>>
>>> At an absolute minimum when you describe an error, PASTE the error
>>> message, complete with traceback, into your message. As it stands, I'm
>>> left wondering which key on your keyboard can possibly "not exist."
>>> Perhaps it's a non-ASCII code, and you're getting some encoding error.
>>> That's a common discrepancy between running from a terminal and running
>>> from some GUI.
>>
>> The error was generated by the program, not Python. The 'key' I was
>> referring to was a dictionary type key, not a physical one on the
>> keyboard.
>>
>>> Even better is to specify the version of Python this program is
>>> presumably written in, and what Linux distro. Then you say it's a GUI
>>> program, so you should specify which GUI library you're using.
>>
>> Python 2.6, Ubuntu 9.10, tkinter
>>
>>> Now if I do a bunch of guessing, I might come up with the likelihood
>>> that your "Nautilus" is supplying a different current directory than the
>>> one the script is located in. You can find that out by looking at:
>>> os.path.abspath(os.curdir)
>>
>> OK, thanks. If that is the case how do I correct it?
>>
>>> But of course how you print that depends on what GUI package you're
>>> running.
>>>
>>> DaveA
>>>
>>
>> Regards, Jim
>>
>>
> You forgot to include the list in your reply. Try using reply-all instead.
>
> If you determine that the current directory is your problem, and that
> Nautilus isn't setting it the way you'd like, then you may have to
> resort to other ways to identify the other files you mention. Easiest
> way might be to use the __file__ attribute of each module, which gives
> its complete path. So your code in the main script could do something
> like (untested):
> target = os.path.dirname(__file__)
> os.chdir(target)

I added target = os.path.dirname(__file__) and printed the result. If I
run the script in Idle it produces the correct result and shows the path
as /usr/bin. Running it form the terminal produces the correct result
but shows the path empty. Running it from Nautilus or a launcher does
not produce the correct result and shows the full path to the directory
that contains the script and its files.

If I add os.chdir(target) to the script, Idle and the terminal stop
producing the correct result and the launcher and Nautilius start
producing the correct result. This is exactly the opposite of what I
expected.

> Better is usually to ignore current directory, and passed the desired
> directory name into whatever function is going to use it.

I'll keep this in mind for anything I write. Right now I'm trying to
understand some examples that were produced in a Windows environment.
Like I said at the top I am new to Linux (Ubuntu) and don't fully
understand its requirements.

> HTH,
>
> DaveA
>
>
Thanks, Jim


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

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