Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread Bruno Piguet
On 11 fév, 22:24, "LL.Snark"  wrote:
> Hi,
>
> I'm looking for a pythonic way to translate this short Ruby code :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=t.index {|x| x1000), "not found")
or
next((i for i, x in enumerate(t) if x>1000), None)
or whatever matches your needs.
Note that if you use the second optionnal argument of next, you'll
need an additional pair of parentheses around
the generator expression which is the first argument of next.

Bruno.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Martin De Kauwe
Steven,

You make some good points and I don't disagree with you. The code is
just a transfer from some older c++ code which had all sorts of
windows menus etc, which isn't required and would make it impossible
to run (again and again). It is not an especially complicated model,
and no doubt there are bugs (though has been used widely for 20
years).

Regarding customisation, in this case it is not a big deal. The way
the code was (arguably poorly) written everything was declared
globally. So in fact by using the .INI file to hold all of them I am
probably saving myself a lot of time and I get away from globals. Most
of those parameters are things I won't change, so I take your point
but I see no issue in having the option frankly (and it is done so
there is no effort now!).

Ordinarily I might do what you said and having method/func calls with
all the params like that, but I felt it was making the code look very
untidy (i.e >5 vars with each call and needing to return > 5 vars). I
then decided it would be better to pass a (single) dictionary or class
object (not sure of correct word here) and I think by referencing it,
e.g. params.light_ext_coeff it is as clear as passing all the values
individually (i.e. you can track where the values came from). I am
happy with this at any rate. Moreover it is what I am used to doing in
C, where I would pass a single structure containing the necessary
values. I also think this is quite standard? I am sure to interface
with scientific libraries (such as GNU GSL) you pass structures in
this way, I was just adopting this method.

The point of this posting was just to ask those that know, whether it
was a bad idea to use the class object in the way I had or was that
OK? And if I should have just used a dictionary, why?

Thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Steven D'Aprano
On Fri, 11 Feb 2011 21:47:32 -0800, Dan Stromberg wrote:

> Did you have some sort of bad experience with pylint?  Do you resent the
> 20 minutes it takes to set it up?

If you read my post more carefully and less defensively, you'll see that 
nothing I said was *opposed* to the use of pylint, merely that pylint is 
not a substitute of a good, thorough test suite.

-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Dan Stromberg
On Fri, Feb 11, 2011 at 4:13 PM, Steven D'Aprano
 wrote:
> On Fri, 11 Feb 2011 10:15:27 -0800, Dan Stromberg wrote:
>
>
>> I'd use a class rather than a dictionary - because with a class, pylint
>> (and perhaps PyChecker and pyflakes?) should be able to detect typos
>> upfront.
>
> *Some* typos. Certainly not all.

The salient bit is not that all typos are (or are not) caught, but
that significantly more typos are caught before they cause a blowup in
production.

> The more complex the code -- and with 100 or so parameters, this sounds
> pretty damn complex -- there is a non-negligible risk of mistakenly using
> the wrong name. Unless pylint now has a "do what I mean, not what I say"
> mode, it can't save you from typos like this:
>
> params.employerID = 23
> params.employeeID = 42
> # much later
> if params.employeeID == 23:
>    # Oops, I meant employ*er*ID
>    ...

No, and yes, and no.

1) No: Pylint can frequently catch variables that are used before they
are set or set but never used
2) Yes: If you write the wrong variable, and it is read somewhere
afterward, you've still got a typo that's essentially a logic bug in
how it manifests
3) No: You should not use variable names that differ by only a single
character, or are too easy to "thinko" for each other - EG it's better
to use params.companyID, params.supervisorID and params.workerID;
these are clearly distinct.

>> With a dictionary, typos remain runtime timebombs.
>
> Are your unit tests broken? You should fix that and not rely on just
> pylint to detect bugs. Unit tests will help protect you against many more
> bugs than just typos.

Unit tests do not replace static analysis; they are complementary techniques.

I started out in the manifestly-typed world.  Then I moved into mostly
python and bash, without any sort of static analysis, and loved it.
More recently, I've been using python with static analysis, and I've
been wondering why I lived without for so long.  That doesn't imply a
rejection of duck typing - it merely means I don't want my code
embarrassing me unnecessarily (though I confess, I find Haskell and
the ML family very interesting for their static, _inferred_ typing).

It's a rare program of much size that can be tested so thoroughly that
static analysis is 100% obviated - especially in the reporting of
error conditions.  An accidental traceback when you're trying to
output an important detail related to one of a few thousand error
conditions is embarrassing, and frequently could be prevented with
pylint.

Also, pylint tends to run much faster than the large battery of
automated tests I prefer to set up.  IOW, it can quickly catch many
kinds of trivial blunders before incurring the development-time
expense of running the full test suite.

> Besides, and I quote...
>
> "I find it amusing when novice programmers believe their main job is
> preventing programs from crashing. ... More experienced programmers
> realize that correct code is great, code that crashes could use
> improvement, but incorrect code that doesn't crash is a horrible
> nightmare." -- Chris Smith

LOL.  Irrespective of some crashes being beneficial, the fact remains
that easily avoided, nonessential crashes should be avoided.  Pylint
enables this to be done for an important class of errors.  To
eliminate them quickly and painlessly isn't precisely an attribute of
a novice.

Did you have some sort of bad experience with pylint?  Do you resent
the 20 minutes it takes to set it up?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reassign or discard Popen().stdout from a server process

2011-02-11 Thread John O'Hagan
On Fri, 11 Feb 2011, Nobody wrote:
> On Thu, 10 Feb 2011 08:35:24 +, John O'Hagan wrote:
> >> > But I'm still a little curious as to why even unsuccessfully
> >> > attempting to reassign stdout seems to stop the pipe buffer from
> >> > filling up.
> >> 
> >> It doesn't. If the server continues to run, then it's ignoring/handling
> >> both SIGPIPE and the EPIPE error. Either that, or another process has
> >> the read end of the pipe open (so no SIGPIPE/EPIPE), and the server is
> >> using non-blocking I/O or select() so that it doesn't block writing its
> >> diagnostic messages.
> > 
> > The server fails with stdout=PIPE if I don't keep reading it, but
> > doesn't fail if I do stdout=anything (I've tried files, strings,
> > integers, and None) soon after starting the process, without any other
> > changes. How is that consistent with either of the above conditions? I'm
> > sure you're right, I just don't understand.
> 
> What do you mean by "fail". I wouldn't be surprised if it hung, due to the
> write() on stdout blocking. If you reassign the .stdout member, the
> existing file object is likely to become unreferenced, get garbage
> collected, and close the pipe, which would prevent the server from
> blocking (the write() will fail rather than blocking).
> 
> If the server puts the pipe into non-blocking mode, write() will fail with
> EAGAIN if you don't read it but with EPIPE if you close the pipe. The
> server may handle these cases differently.

By "fail" I mean the server, which is the Fluidsynth soundfont rendering 
program, stops producing sound in a way consistent with the blocked write() as 
you describe. It continues to read stdin; in fact, Ctrl+C-ing out of the block 
produces all the queued sounds at once. 

What I didn't realise was that the (ineffective) reassignment of stdout has the 
side-effect of closing it by dereferencing it, as you explain above. I asked on 
the Fluidsynth list and currently it ignores if the pipe it's writing to has 
been closed . All makes sense now, thanks.


John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop comprehensions

2011-02-11 Thread Terry Reedy

On 2/11/2011 6:10 PM, Benjamin S Wolf wrote:

It occurred to me as I was writing a for loop that I would like to
write it in generator comprehension syntax, eg.

   for a in b if c:


Already proposed and rejected. See archives for python-ideas or the 
gmane.comp.python.ideas mirror.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread Terry Reedy

On 2/11/2011 4:24 PM, LL.Snark wrote:

Hi,

I'm looking for a pythonic way to translate this short Ruby code :
t=[6,7,8,6,7,9,8,4,3,6,7]
i=t.index {|x| x

What does Ruby do if there is no such element?
For Python, the answer should be either None or ValueError.



If can write it in python several ways :
t=[6,7,8,6,7,9,8,4,3,6,7]
i=0
while t[i]>=t[0] : i+=1


This will raise IndexError when i gets too big.


... not pythonic I think...

Or :
t=[6,7,8,6,7,9,8,4,3,6,7]
i=[j for j in range(len(t)) if t[j]

This will raise IndexError if the list is empty.

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing binary files in windows

2011-02-11 Thread Nick Raptis

On 02/12/2011 05:20 AM, Abhishek Gulyani wrote:

When I write binary files in windows:

file  = open(r'D:\Data.bin','wb')
file.write('Random text')
file.close()

and then open the file it just shows up as normal text. There is 
nothing binary about it. Why is that?


Sorry if this is too much of a noobie question. I tried googling 
around but couldn't find an answer.


But then, you opened the file you created in Notepad and saw that the 
lines weren't wrapping maybe?


It all comes down to Line endings. Read here to see what LF vs. CRLF is 
all about http://en.wikipedia.org/wiki/Newline#Representations


You see, when you read a file, Python converts both LF and CRLF to "\n". 
When you write a "\n" to a file Python writes CRLF in Windows and just 
LF in Unix machines.
That'd be a heck troublesome when dealing with binary files, hence the 
'b' flag. It basically means *Don't convert newlines", and it's pretty 
common in software.


So, to answer your question: If you're only writing text to a file, 
you'll only see a difference if your external text editor isn't smart 
enough to treat both LF and CRLF as newlines. Like Notepad did back in 
the day, and maybe still does.
But if you're writing binary stuff, it makes all the difference in the 
world.


Nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing binary files in windows

2011-02-11 Thread Corey Richardson
On 02/11/2011 10:20 PM, Abhishek Gulyani wrote:
> When I write binary files in windows:
> 
> file  = open(r'D:\Data.bin','wb')
> file.write('Random text')
> file.close()
> 
> and then open the file it just shows up as normal text. There is nothing
> binary about it. Why is that?
> 
> Sorry if this is too much of a noobie question. I tried googling around but
> couldn't find an answer.
> 

It is binary! What are you expecting? You wrote text to a file, so when
you open the file with whatever, it displays like text. Even when you
don't open a file as binary, it is still a binary file. Otherwise it
wouldn't exist.
-- 
http://mail.python.org/mailman/listinfo/python-list


Writing binary files in windows

2011-02-11 Thread Abhishek Gulyani
When I write binary files in windows:

file  = open(r'D:\Data.bin','wb')
file.write('Random text')
file.close()

and then open the file it just shows up as normal text. There is nothing
binary about it. Why is that?

Sorry if this is too much of a noobie question. I tried googling around but
couldn't find an answer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parse html rendered by js

2011-02-11 Thread yanghq
thank u for your reply.

yeah, my end goal is something like screen scraping a web site.

Duplicating the Javascript behaviour in my Python code will be a huge
burden,I'm afraid time can't aford it.

someone say that webkit / pamie and other browser engine can render js
to html,but pamie is only work for windows, and webkit is hard to
retrieve for me.I am searching other browser engine.

On Fri, 2011-02-11 at 06:46 -0800, Alex Willmer wrote:
> On Feb 11, 8:20 am, yanghq  wrote:
> > hi,
> > I wanna get attribute value like href,src... in html.
> >
> > for simple html page libxml2dom can help me parse it into dom, and
> > get what  I want;
> >
> > but for some pages rendered by js, like:
> >
> > document.write(
> > ' > onUnload="end()" onResize="change()">'+
> >   ''+
> > ' > src="../frame.html?rtfPossible=' + rtfPossibleString + '">'+
> > ...
> > )
> > how can I get the atrribute value of 'src', thank you for any help.
> 
> You can
> - Duplicate the Javascript behaviour in your Python code (i.e. rewrite
> it yourself). Whenever the javascript changes you will need to update
> your duplicate code.
> - Use or write a Python module that uses a web browser to download/
> execute the page. I'm not aware of any that exist.
> 
> Neither option is very good, and that is one reason why such
> Javascript is considered bad practise. What is your end goal - e.g.
> testing a web application, screen scraping a web site)? There may be a
> better way.
> 
> Alex



---
Confidentiality Notice: The information contained in this e-mail and any 
accompanying attachment(s) 
is intended only for the use of the intended recipient and may be confidential 
and/or privileged of 
Neusoft Corporation, its subsidiaries and/or its affiliates. If any reader of 
this communication is 
not the intended recipient, unauthorized use, forwarding, printing,  storing, 
disclosure or copying 
is strictly prohibited, and may be unlawful.If you have received this 
communication in error,please 
immediately notify the sender by return e-mail, and delete the original message 
and all copies from 
your system. Thank you. 
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with giant font sizes in tkinter

2011-02-11 Thread Steven D'Aprano
On Fri, 11 Feb 2011 01:29:02 -0500, Chris Jones wrote:

>> >> labelfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*'

[...]

> First of all, you need to know precisely what the above font name coding
> means.
[...]
>   http://www.archive.org/details/xwindowsytemosf03querarch


Thanks for the link, that's incredibly useful (although the PDF doesn't 
render correctly in any of the five different PDF viewers I tried, but I 
was able to read it). 


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop comprehensions

2011-02-11 Thread Steven D'Aprano
On Fri, 11 Feb 2011 16:59:52 -0700, Ian Kelly wrote:

> Why not allow the same thing in for-loop conditions?  

Because new syntax and new language features means more work. Somebody 
has to write the code, make sure that it doesn't break existing Python 
code, test it for bugs, change the documentation, write regression tests 
for it... And then, having done it for CPython, somebody else has to do 
the same for IronPython, Jython, PyPy, CLPython, Stackless ... And all 
that code has to be maintained.

Because new syntax and features increases the size and complexity of the 
Python code base, which means more bugs and more tests needed.

Because new syntax and features increases the size and complexity of the 
documentation needed, and hence increases the amount of things that need 
to be learned.

Because the guiding philosophy of Python is "there should be one, and 
preferably only one, obvious way to do it". That doesn't mean that 
multiple ways of doing it are forbidden (far from it!) but it does mean 
that Python is conservative about adding multiple ways of spelling the 
same thing.

New features don't come for free. They have costs too. You need something 
more than just "why not" to justify adding features -- you also need a 
"why" as well.

So... why add extra syntax to for loops when they're already very simple 
and effective? 

There's nothing wrong with writing

for x in iterable:
if condition(x):
process(x)

The existing syntax is clear and obvious. There's no clear benefit to 
shifting the if clause to the for expression: it complicates the parser, 
and any benefit (if any!) only applies to a tiny fraction of for loops. 
You save one line, which is trivial. You may save one indentation level, 
which might, sometimes, be useful, but more often will also be trivial. 
If there's an advantage to the suggestion, it's small.


> I think that
> anything that makes the language syntax more consistent is good.

"A foolish consistency is the hobgoblin of little minds."

Consistency, in and of itself, is not a virtue.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Steven D'Aprano
On Fri, 11 Feb 2011 16:31:09 -0800, Martin De Kauwe wrote:

> The 100+ parameters just means "everything" can be adjusted outside of
> the code, invariable most of it isn't.

If people aren't going to change all these parameters, why are you 
spending the time and energy writing code for something that won't happen?

There are *real costs* to increasing the amount of customization people 
can do with your code. The more complex your code, the more bugs it will 
contain. You should consider this almost a law of nature.

The more power you give people to change parameters, the more often they 
will hit unexpected interactions between parameters that you never 
imagined. You should expect bug reports that will take forever to track 
down, because (for example) the bug only occurs when param #37 is larger 
than param #45, but only if param #62 is less than param #5 and both are 
less than 100 and param #83 is a multiple of 17...

The more complex your code, the more tests you will need to be sure the 
code does what you expect. The number of combinations that need testing 
*explodes* exponentially. You simply cannot test every combination of 
parameters. Untested code should be considered buggy until proven 
otherwise.

Think very carefully before allowing over-customization. Take into 
account the costs as well as the benefits. Then, if you still decide to 
allow all that customization, at least you know that the pain will be 
worth it.


> As I said I am happy to consider a dictionary, although some of the
> calculations are quite complex and I *think* it is easier to read this
> way, rather than with a dictionary.

I believe that most of these calculations should be written as functions 
which take arguments. This will allow better testing and customization. 
Instead of writing complex calculations inline, you should make them 
functions or methods. There's little difference in complexity between:

my_calculation(arg1, arg2, arg3, params.x, params.y, params.z)

and

my_calculation(arg1, arg2, arg3, params['x'], params['y'], params['z'])

(although, as you have realised, the second is a little more visually 
noisy -- but not that much).

Better still, have the function use sensible default values:

def my_calculation(arg1, arg2, arg3, x=None, y=None, z=None):
if x is None: 
x = params.x  # or params['x'], who cares?
if y is None:
y = params['y']  # or params.x
...


This gives you the best of both worlds: you can supply parameters at 
runtime, for testing or customization, but if you don't, the function 
will use sensible defaults.


> That is purely an opinion, I don't
> have a computer science background and so I am asking really, is what I
> am doing very bad, and if so why? What do other people do? I have tried
> to search a lot on this subject but I find the example not very
> specific, (or I am reading the wrong places).

Whether you use obj.x or obj['x'] is the least important part of the 
problem. That's merely syntax.




-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Martin De Kauwe
On Feb 12, 11:13 am, Steven D'Aprano  wrote:
> On Fri, 11 Feb 2011 10:15:27 -0800, Dan Stromberg wrote:
> > I'd use a class rather than a dictionary - because with a class, pylint
> > (and perhaps PyChecker and pyflakes?) should be able to detect typos
> > upfront.  
>
> *Some* typos. Certainly not all.
>
> The more complex the code -- and with 100 or so parameters, this sounds
> pretty damn complex -- there is a non-negligible risk of mistakenly using
> the wrong name. Unless pylint now has a "do what I mean, not what I say"
> mode, it can't save you from typos like this:
>
> params.employerID = 23
> params.employeeID = 42
> # much later
> if params.employeeID == 23:
>     # Oops, I meant employ*er*ID
>     ...
>
> > With a dictionary, typos remain runtime timebombs.
>
> Are your unit tests broken? You should fix that and not rely on just
> pylint to detect bugs. Unit tests will help protect you against many more
> bugs than just typos.
>
> Besides, and I quote...
>
> "I find it amusing when novice programmers believe their main job is
> preventing programs from crashing. ... More experienced programmers
> realize that correct code is great, code that crashes could use
> improvement, but incorrect code that doesn't crash is a horrible
> nightmare." -- Chris Smith
>
> --
> Steven

The 100+ parameters just means "everything" can be adjusted outside of
the code, invariable most of it isn't. I am setting this up with some
bayesian calibration in mind. A lot of those parameters will be
switches as well. I think perhaps I will write a defaults module and
just read a .INI file with the values the user wants changing.
Originally I was just going to read everything in, but maybe this is
better from a usage point of view.

As I said I am happy to consider a dictionary, although some of the
calculations are quite complex and I *think* it is easier to read this
way, rather than with a dictionary. That is purely an opinion, I don't
have a computer science background and so I am asking really, is what
I am doing very bad, and if so why? What do other people do? I have
tried to search a lot on this subject but I find the example not very
specific, (or I am reading the wrong places).

thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 32-bit on Windows 64-bit

2011-02-11 Thread MRAB

On 11/02/2011 21:50, Sherm Pendley wrote:

"Martin v. Loewis"  writes:


Am 11.02.2011 19:41, schrieb Craig Yoshida:

what kind of memory limitations to processes running on 32-bit python
(with 32-bit C extensions like scipy) have on 64-bit Windows?   I'm
having occasional MemoryErrors when running a python program on
64-bit Windows 7 that runs fine on my OS X machine.  Both machines
are using a 64-bit OS and have 4GB of RAM.


In addition to the limitations Michel reports: on a 32-bit system,
objects are typically limited to using at most 2GiB, per object
(of course, you could have at most two objects that come close to
this size, since the whole address space would not be larger than
4GiB).


IIRC, 32-bit Windows programs are limited to 2GiB, reserving the rest
of the virtual address space for Windows' own use.


It's possible to configure 32-bit Windows to allow up to 3GB user RAM.


Also, 32-bit apps remain 32-bit, even if they're running on a 64-bit
capable OS. Assuming you're running Snow Leopard on your Mac, you're
using a 64-bit Python interpreter *and* a 64-bit OS. You need to have
both to take advantage of a 64-bit memory space.


--
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Martin De Kauwe
Sorry I should have added a little more example to help with clarity?
So after reading the .INI file I then initialise the objects I
described e.g.

 def initialise_simulation(self):
"""Set the initial conditions.

using values from the .ini value set the C and N pools
and other misc states.

"""
for attr, value in self.initial_state.__dict__.iteritems():
#print attr, value
setattr(self.pools, attr, value)

# maybe need M2_AS_HA here?
self.pools.lai = self.params.sla * self.params.cfrac_dry_mass
self.fluxes.nuptake = 0.0
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread LL.Snark

On 11/02/2011 22:24, LL.Snark wrote:

Hi,

I'm looking for a pythonic way to translate this short Ruby code :
t=[6,7,8,6,7,9,8,4,3,6,7]
i=t.index {|x| x=t[0] : i+=1

... not pythonic I think...

Or :
t=[6,7,8,6,7,9,8,4,3,6,7]
i=[j for j in range(len(t)) if t[j]


Thx for your answers.

May I add some comments ?

=
t = [6,7,8,6,7,9,8,4,3,6,7]
i = -1
for index, item in enumerate(t):
if item < t[0]:
i = index
break

is OK for me, while a bit too long :)
==
from itertools import dropwhile
t=[6,7,8,6,7,9,8,4,3,6,7]
i = dropwhile(lambda k: t[k]>=t[0], t).__next__()
(I added the __ around next. Am i true ?)

This does not work for me.

i is effectively 7, but 7 is the second item of the array.
If you try :
t=[6,8,8,6,7,9,8,4,3,6,7]
i = dropwhile(lambda k: t[k]>=t[0], t).__next__()
You will get 8.

I guess this is because k is a value of the array, not an index.
In the first example, we compare t[6], then t[7], then t[8], t[6], t[7] 
etc... to t[0].
(It happens that the first item of the list is dropped... then the first 
element of the resulting list is 7... the answer... but it was just luck)


=
The javalicious one :

class ComparisonPredicate:
def __init__(self, func):
self.func = func
def __eq__(self, other):
return self.func(other)

t = [6, 7, 8, 6, 7, 9, 8, 4, 3, 6, 7]
print(t.index(ComparisonPredicate(lambda x: x < t[0])))

It took me some time to understand :)
It's a shame there is no built-in object like ComparisonPredicate, 
because the line t.index(ComparisonPredicate(lambda x: x < t[0])) looks 
good to me.


===
Finally, the other enumerate solution may be written like this :
t = [6,7,8,6,7,9,8,4,3,6,7]
for i, j in enumerate(t):
if j < t[0]: break
else : i=-1
Quite short.

=
Finally, with your solutions, I build another one. Here it is :
t=[6,7,8,6,7,9,8,4,3,6,7]
i,j=filter(lambda x: x[1]=t[0],enumerate(t)).__next__()

Or else :
t=[6,7,8,6,7,9,8,4,3,6,7]
t.index(filter(lambda x: xThe last one behaves like the Ruby one, if a value is found. If no walue 
is found, the Python code raises a StopException. With the Ruby code, i 
is nil.


Is there another way to access the first item of an iterator ?
( __next__() is ugly )

==
Paul, the Ruby version stops when it finds the first matching element
t=[6,7,8,6,7,9,8,4,3,6,7]
i=t.index {|x| x(I figured this out by making a 1 000 000 elements array. It was faster 
with a matching value at the beginning of the array)


Many thanks for your answers





--
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Steven D'Aprano
On Fri, 11 Feb 2011 10:15:27 -0800, Dan Stromberg wrote:


> I'd use a class rather than a dictionary - because with a class, pylint
> (and perhaps PyChecker and pyflakes?) should be able to detect typos
> upfront.  

*Some* typos. Certainly not all.

The more complex the code -- and with 100 or so parameters, this sounds 
pretty damn complex -- there is a non-negligible risk of mistakenly using 
the wrong name. Unless pylint now has a "do what I mean, not what I say" 
mode, it can't save you from typos like this:

params.employerID = 23
params.employeeID = 42
# much later
if params.employeeID == 23:
# Oops, I meant employ*er*ID
...



> With a dictionary, typos remain runtime timebombs.

Are your unit tests broken? You should fix that and not rely on just 
pylint to detect bugs. Unit tests will help protect you against many more 
bugs than just typos.

Besides, and I quote...


"I find it amusing when novice programmers believe their main job is 
preventing programs from crashing. ... More experienced programmers 
realize that correct code is great, code that crashes could use 
improvement, but incorrect code that doesn't crash is a horrible 
nightmare." -- Chris Smith



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop comprehensions

2011-02-11 Thread Ian Kelly
On Fri, Feb 11, 2011 at 4:47 PM, Westley Martínez  wrote:
> No, too confusing. Then people'll want compound loops e.g.:
>
> for a in b if c while d else return x:
>    print('Ha ha I'm so clever!')

I've yet to see anybody arguing for while loops to be nested like
that, but we already allow nested for loops in comprehensions and
generator expressions:

[(x, y) for x in a for y in b if c(y)]

Why not allow the same thing in for-loop conditions?  I think that
anything that makes the language syntax more consistent is good.

Cheers,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Martin De Kauwe
Hi,

yes I read a .INI file using ConfigParser, just similar sections (in
my opinion) to make one object which i can then pass to different
classes. E.G.

class Dict2Obj:
""" Turn a dictionary into an object.

The only purpose of this is that I think it is neater to reference
values
x.soiltemp rather than x['soiltemp'] ;P
"""
def __init__(self, dict):

for k, v in dict.items():
setattr(self, k, v)


class Parser(object):
""" Load up all the initialisation data.

Return the met data as an array, perhaps we should really also
return a
header as well? Return the ini file as various objects.

"""
def __init__(self, ini_fname, met_fname):

self.ini_fname = ini_fname
self.met_fname = met_fname

def load_files(self):

# read the driving data in, this may get more complicated?
met_data = met_data = np.loadtxt(self.met_fname, comments='#')

# read the configuration file into a different dicts, break up
# into model_params, control and state
config = ConfigParser.RawConfigParser()
config.read(self.ini_fname)

# params
model_params = {}
sections =
['water','nitra','soilp','carba','litter','envir','prodn']
for section in sections:
for option in config.options(section):
model_params[option] = config.getfloat(section,
option)

# turn dict into an object
model_params = Dict2Obj(model_params)

# control
control = {}
for option in config.options('control'):
control[option] = config.getint('control', option)

# turn dict into an object
control = Dict2Obj(control)

initial_state = {}
sections = ['cinit','ninit','vinit']
for section in sections:
for option in config.options(section):
initial_state[option] = config.getfloat(section,
option)

# turn dict into objects
initial_state = Dict2Obj(initial_state)

return (initial_state, control, model_params,
met_data)

So I would then pass these objects through my code, for example a
given class would just expect to inherit params perhaps.

class calc_weight(object):

def __init__(self, params):
self.params = params

There are also "states" that evolve through the code which various
methods of a given class change. For example lets call it elephants
weight. So the model will do various things to predict changes in our
elephants weight, so there will be a class to calculate his/her food
intake etc. Using this example the other thing I wanted to do was pass
"states" around like self.elephant_weight. However it occurred to me
if I just used self.elephant_weight for example it would make it
harder to call individual components seperately, so better to stick to
the same method and using an object i reasoned. Hence I started with
my emptydict thing, I hope that helps make it clearer?

class EmptyObject:
pass


# generate some objects to store pools and fluxes...
self.pools = EmptyObject()

# add stuff to it
self.pools.elephant_weight = 12.0

thanks for all of the suggestions it is very insightful
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop comprehensions

2011-02-11 Thread Westley Martínez
On Fri, 2011-02-11 at 15:10 -0800, Benjamin S Wolf wrote:
> It occurred to me as I was writing a for loop that I would like to
> write it in generator comprehension syntax, eg.
> 
>   for a in b if c:
> 
> rather than using one of the more verbose but allowable syntaxes:
> 
>   for a in (x for x in b if c):
> 
>   for a in b:
> if not c: continue
> 
> Python 3.1 does not support "for comprehensions", and a few cursory
> searches of PEPs and this list don't turn up anything. I like the idea
> enough to suggest it though I'm unfamiliar with the PEP/feature
> request process (PEP 1 pointed me here). What do other people think?
> 
> --Ben
No, too confusing. Then people'll want compound loops e.g.:

for a in b if c while d else return x:
print('Ha ha I'm so clever!')

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop comprehensions

2011-02-11 Thread Jon Clements
On Feb 11, 11:10 pm, Benjamin S Wolf  wrote:
> It occurred to me as I was writing a for loop that I would like to
> write it in generator comprehension syntax, eg.
>
>   for a in b if c:
>
> rather than using one of the more verbose but allowable syntaxes:
>
>   for a in (x for x in b if c):
>
>   for a in b:
>     if not c: continue
>
> Python 3.1 does not support "for comprehensions", and a few cursory
> searches of PEPs and this list don't turn up anything. I like the idea
> enough to suggest it though I'm unfamiliar with the PEP/feature
> request process (PEP 1 pointed me here). What do other people think?
>
> --Ben

Can't help with the PEP stuff, but ummm... is anything wrong with
filter()? For some things, I personally find it more readable in some
circumstances than list/gen comps. I don't mind predicates at "the
end", but sometimes they're more obvious at "the front".

Jon.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread Jon Clements
On Feb 11, 9:24 pm, "LL.Snark"  wrote:
> Hi,
>
> I'm looking for a pythonic way to translate this short Ruby code :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=t.index {|x| x
> If you don't know Ruby, the second line means :
> What is the index, in array t, of the first element x such that x
> If can write it in python several ways :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=0
> while t[i]>=t[0] : i+=1
>
> ... not pythonic I think...
>
> Or :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=[j for j in range(len(t)) if t[j]
> ...too cryptic...
>
> I'm using Python 3.
>
> Thx

My take (but using Python 2.x):

import operator as op
from functools import partial
from itertools import islice

t = [6,7,8,6,7,9,8,4,3,6,7]

def first_conditional(seq, first=op.itemgetter(0), pred=op.gt):
f = first(seq)
cmpfunc = partial(pred, f)
for idx, val in enumerate(islice(seq, 1, None)):
if cmpfunc(val): return idx + 1
return -1 # or raise an exception?


Off top of head, so needs work, but is fairly generic.

Jon.
-- 
http://mail.python.org/mailman/listinfo/python-list


For loop comprehensions

2011-02-11 Thread Benjamin S Wolf
It occurred to me as I was writing a for loop that I would like to
write it in generator comprehension syntax, eg.

  for a in b if c:

rather than using one of the more verbose but allowable syntaxes:

  for a in (x for x in b if c):

  for a in b:
if not c: continue

Python 3.1 does not support "for comprehensions", and a few cursory
searches of PEPs and this list don't turn up anything. I like the idea
enough to suggest it though I'm unfamiliar with the PEP/feature
request process (PEP 1 pointed me here). What do other people think?

--Ben
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asterisk sign before the 'self' keyword

2011-02-11 Thread Steven D'Aprano
On Fri, 11 Feb 2011 07:06:11 -0800, christian.posta wrote:

> Within the __call__ function for a class, I saw a method of that class
> referred to like this:
> 
> *self.()
> 
> The brackets indicate the method name. What does the *self refer to??
> Does it somehow indicate the scope of the 'self' variable? Thanks in
> advance...


self is not a keyworld. It is an ordinary variable name like any other, 
except that by convention it is used to refer to the instance inside 
methods.

Without knowing the context, *self.method() could mean at least one of 
two things:

(1) Ordinary multiplication:

result = 42*self.method()

This is like: 

temp = self.method()
result = 42*temp


(2) Positional argument unpacking:

result = function(*self.method())

This is like:

temp = self.method()
result = function(temp[0], temp[1], temp[2], ...)

or if you prefer, like the old and now deprecated function:

result = apply(function, temp)



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread Paul Rubin
"LL.Snark"  writes:

> I'm looking for a pythonic way to translate this short Ruby code :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=t.index {|x| x=t[0], t).next()

Note the above can throw an exception if no suitable element is found.

t=[6,7,8,6,7,9,8,4,3,6,7]
i=[j for j in range(len(t)) if t[j]http://mail.python.org/mailman/listinfo/python-list


Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread Dan Stromberg
On Fri, Feb 11, 2011 at 1:51 PM, Dan Stromberg  wrote:
> On Fri, Feb 11, 2011 at 1:43 PM, André Roberge  
> wrote:
>> On Friday, February 11, 2011 5:24:15 PM UTC-4, LL.Snark wrote:
>>> Hi,
>>>
>>> I'm looking for a pythonic way to translate this short Ruby code :
>>> t=[6,7,8,6,7,9,8,4,3,6,7]
>>> i=t.index {|x| x>>
>>> If you don't know Ruby, the second line means :
>>> What is the index, in array t, of the first element x such that x>>
>>> If can write it in python several ways :
>>> t=[6,7,8,6,7,9,8,4,3,6,7]
>>> i=0
>>> while t[i]>=t[0] : i+=1
>>>
>>> ... not pythonic I think...
>>>
>>> Or :
>>> t=[6,7,8,6,7,9,8,4,3,6,7]
>>> i=[j for j in range(len(t)) if t[j]>>
>>> ...too cryptic...
>>>
>> You could go with something like (untested)
>> t = [6,7,8,6,7,9,8,4,3,6,7]
>> for i, j in enumerate(t):
>>    if j < t[0]:
>>        break
>> else:
>>        i = 0
>>
>> ;-)
>>
>>
>>
>>> I'm using Python 3.
>>>
>>> Thx
>
 t = [6,7,8,6,7,9,8,4,3,6,7]
 generator = (element for element in t[1:] if element >= t[0])
 print(next(generator))
>

Oops; a correction.  Fast and concise - and if you decide you need the
2nd or 10th, they'll be on their way as soon as you request them (lazy
evaluation):

>>> generator = (ind+1 for ind, element in enumerate(t[1:]) if element >= t[0])
>>> print(next(generator))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread Josh Benner
On Fri, Feb 11, 2011 at 1:51 PM, Dan Stromberg  wrote:

> On Fri, Feb 11, 2011 at 1:43 PM, André Roberge 
> wrote:
> > On Friday, February 11, 2011 5:24:15 PM UTC-4, LL.Snark wrote:
> >> Hi,
> >>
> >> I'm looking for a pythonic way to translate this short Ruby code :
> >> t=[6,7,8,6,7,9,8,4,3,6,7]
> >> i=t.index {|x| x >>
> >> If you don't know Ruby, the second line means :
> >> What is the index, in array t, of the first element x such that x >>
> >> If can write it in python several ways :
> >> t=[6,7,8,6,7,9,8,4,3,6,7]
> >> i=0
> >> while t[i]>=t[0] : i+=1
> >>
> >> ... not pythonic I think...
> >>
> >> Or :
> >> t=[6,7,8,6,7,9,8,4,3,6,7]
> >> i=[j for j in range(len(t)) if t[j] >>
> >> ...too cryptic...
> >>
> > You could go with something like (untested)
> > t = [6,7,8,6,7,9,8,4,3,6,7]
> > for i, j in enumerate(t):
> >if j < t[0]:
> >break
> > else:
> >i = 0
> >
> > ;-)
> >
> >
> >
> >> I'm using Python 3.
> >>
> >> Thx
>
> >>> t = [6,7,8,6,7,9,8,4,3,6,7]
> >>> generator = (element for element in t[1:] if element >= t[0])
> >>> print(next(generator))
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Since we only care about the 1st generated value ...

t = [6,7,8,6,7,9,8,4,3,6,7]
t.index(next((elem for elem in t[1:] if elem < t[0])))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread Ian
On Feb 11, 2:24 pm, "LL.Snark"  wrote:
> Hi,
>
> I'm looking for a pythonic way to translate this short Ruby code :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=t.index {|x| xhttp://mail.python.org/mailman/listinfo/python-list


Re: Python 32-bit on Windows 64-bit

2011-02-11 Thread Sherm Pendley
"Martin v. Loewis"  writes:

> Am 11.02.2011 19:41, schrieb Craig Yoshida:
>> what kind of memory limitations to processes running on 32-bit python
>> (with 32-bit C extensions like scipy) have on 64-bit Windows?   I'm
>> having occasional MemoryErrors when running a python program on
>> 64-bit Windows 7 that runs fine on my OS X machine.  Both machines
>> are using a 64-bit OS and have 4GB of RAM.
>
> In addition to the limitations Michel reports: on a 32-bit system,
> objects are typically limited to using at most 2GiB, per object
> (of course, you could have at most two objects that come close to
> this size, since the whole address space would not be larger than
> 4GiB).

IIRC, 32-bit Windows programs are limited to 2GiB, reserving the rest
of the virtual address space for Windows' own use.

Also, 32-bit apps remain 32-bit, even if they're running on a 64-bit
capable OS. Assuming you're running Snow Leopard on your Mac, you're
using a 64-bit Python interpreter *and* a 64-bit OS. You need to have
both to take advantage of a 64-bit memory space.

sherm--

-- 
Sherm Pendley
   
Cocoa Developer
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread Dan Stromberg
On Fri, Feb 11, 2011 at 1:43 PM, André Roberge  wrote:
> On Friday, February 11, 2011 5:24:15 PM UTC-4, LL.Snark wrote:
>> Hi,
>>
>> I'm looking for a pythonic way to translate this short Ruby code :
>> t=[6,7,8,6,7,9,8,4,3,6,7]
>> i=t.index {|x| x>
>> If you don't know Ruby, the second line means :
>> What is the index, in array t, of the first element x such that x>
>> If can write it in python several ways :
>> t=[6,7,8,6,7,9,8,4,3,6,7]
>> i=0
>> while t[i]>=t[0] : i+=1
>>
>> ... not pythonic I think...
>>
>> Or :
>> t=[6,7,8,6,7,9,8,4,3,6,7]
>> i=[j for j in range(len(t)) if t[j]>
>> ...too cryptic...
>>
> You could go with something like (untested)
> t = [6,7,8,6,7,9,8,4,3,6,7]
> for i, j in enumerate(t):
>    if j < t[0]:
>        break
> else:
>        i = 0
>
> ;-)
>
>
>
>> I'm using Python 3.
>>
>> Thx

>>> t = [6,7,8,6,7,9,8,4,3,6,7]
>>> generator = (element for element in t[1:] if element >= t[0])
>>> print(next(generator))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread Chris Rebert
On Fri, Feb 11, 2011 at 1:24 PM, LL.Snark  wrote:
> Hi,
>
> I'm looking for a pythonic way to translate this short Ruby code :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=t.index {|x| x
> If you don't know Ruby, the second line means :
> What is the index, in array t, of the first element x such that x
> If can write it in python several ways :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=0
> while t[i]>=t[0] : i+=1
>
> ... not pythonic I think...
>
> Or :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=[j for j in range(len(t)) if t[j]
> ...too cryptic...
>
> I'm using Python 3.

My version:

t = [6,7,8,6,7,9,8,4,3,6,7]
i = -1
for index, item in enumerate(t):
if item < t[0]:
i = index
break

I'm a big fan of enumerate().
I'm sure an itertools solution is also possible.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread André Roberge
On Friday, February 11, 2011 5:24:15 PM UTC-4, LL.Snark wrote:
> Hi,
> 
> I'm looking for a pythonic way to translate this short Ruby code :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=t.index {|x| x 
> If you don't know Ruby, the second line means :
> What is the index, in array t, of the first element x such that x 
> If can write it in python several ways :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=0
> while t[i]>=t[0] : i+=1
> 
> ... not pythonic I think...
> 
> Or :
> t=[6,7,8,6,7,9,8,4,3,6,7]
> i=[j for j in range(len(t)) if t[j] 
> ...too cryptic...
> 
You could go with something like (untested)
t = [6,7,8,6,7,9,8,4,3,6,7]
for i, j in enumerate(t):
if j < t[0]:
break
else:
i = 0

;-)



> I'm using Python 3.
> 
> Thx

-- 
http://mail.python.org/mailman/listinfo/python-list


Arrays/List, filters, Pytho, Ruby

2011-02-11 Thread LL.Snark

Hi,

I'm looking for a pythonic way to translate this short Ruby code :
t=[6,7,8,6,7,9,8,4,3,6,7]
i=t.index {|x| x=t[0] : i+=1

... not pythonic I think...

Or :
t=[6,7,8,6,7,9,8,4,3,6,7]
i=[j for j in range(len(t)) if t[j]http://mail.python.org/mailman/listinfo/python-list


Re: Python 32-bit on Windows 64-bit

2011-02-11 Thread Martin v. Loewis
Am 11.02.2011 19:41, schrieb Craig Yoshida:
> what kind of memory limitations to processes running on 32-bit python
> (with 32-bit C extensions like scipy) have on 64-bit Windows?   I'm
> having occasional MemoryErrors when running a python program on
> 64-bit Windows 7 that runs fine on my OS X machine.  Both machines
> are using a 64-bit OS and have 4GB of RAM.

In addition to the limitations Michel reports: on a 32-bit system,
objects are typically limited to using at most 2GiB, per object
(of course, you could have at most two objects that come close to
this size, since the whole address space would not be larger than
4GiB).

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Another related OO Python ?

2011-02-11 Thread Doug Epling
hey, does anyone find the UML useful during Python development of larger 
projects?

--
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Jean-Michel Pichavant

Martin De Kauwe wrote:

Hi,

I have a series of parameter values which i need to pass throughout my
code (>100), in C I would use a structure for example. However in
python it is not clear to me if it would be better to use a dictionary
or build a class object? Personally I think accessing the values is
neater (visually) with an object rather than a dictionary, e.g.

x = params['price_of_cats'] * params['price_of_elephants']

vs.

x = params.price_of_cats * params.price_of_elephants

So currently I am building a series of class objects to hold different
parameters and then passing these through my code, e.g.

class EmptyObject:
pass

self.animal_prices = EmptyObject()
self.price_of_cats = 12 or reading a file and populating the object


I would be keen to hear any reasons why this is a bad approach (if it
is, I haven't managed to work this out)? Or perhaps there is a better
one?

thanks

Martin
  

Using classes is the best choice.

However, if because there would be too much classes to define so that 
you are forced to use your EmptyObject trick, adding attributes to the 
inntance dynamically, I'd say that dictionnaries are a more common pattern.


Ideally, you would have something like:

class PriceHolder(object):
   @classmethod
   def fromFile(cls, filename):
  # example of abstract method
  pass

class Animals(PriceHolder):
   def __init__(self):
  self.cat = None
  self.elephant = None

class Fruits(PriceHolder):
   def __init__(self):
  self.banana = None
  self.apple = None


Then you would have to write 100 PriceHolder subclasses...

JM
--
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Andrea Crotti

Il giorno 11/feb/2011, alle ore 19.47, Ethan Furman ha scritto:

> 
> I strongly disagree.  Code readability is one of the most important issues.

Perfectly agree with that, but

obj.name = x
obj.surname = y

obj['name'] = x
obj['surname'] = y

are both quite readable in my opinion.
Other things are more important to evaluate in this case.

I normally always wrap dictionaries because before or later I'll want to add 
some other
features, but I don't know if that's the  case here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asterisk sign before the 'self' keyword

2011-02-11 Thread Ulrich Eckhardt
Hmmm.

Is it just us that read this topic and think of an object with a psychic 
disorder like multiple personalities?

:):

TGIF.

Uli

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 32-bit on Windows 64-bit

2011-02-11 Thread Michel Claveau - MVP
Hi!

Python 32 bits (& Pywin32) limits are:
  2 GB on win.7_32 bits
  4 GB on win.7_64 bits

That's what I found in my tests.

@-salutations
-- 
Michel Claveau 






-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing functions

2011-02-11 Thread DataSmash
Appreciate the responses, guys.
I now see the difference between the ways I was trying to call
function(s).
R.D.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO Python

2011-02-11 Thread Paul Symonds

Thank you

--
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Miki Tebeka
> I have a series of parameter values which i need to pass throughout my
> code (>100), in C I would use a structure for example. However in
> python it is not clear to me if it would be better to use a dictionary
> or build a class object?
namedtuple can be a quick and easy solution for you.
http://docs.python.org/dev/library/collections.html#collections.namedtuple

HTH
--
Miki Tebeka 
http://pythonwise.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Bill Felton
>From an old-time Smalltalker / object guy, take this for whatever it's worth.
The *primary* reason for going with a class over a dictionary is if there is 
specific behavior that goes along with these attributes.
If there isn't, if this is "just" an 'object store', there's no reason not to 
use a dictionary.  
After all, it is not too far off the mark to say a class is just a dictionary 
with it's own behavior set...
As another poster pointed out, 100 (or more) attributes is an oddity, I would 
call it a 'code smell'.  Whereas a dictionary with 100 entries is no big deal 
at all.
But for me, the big deciding factor comes down to whether or not there is 
specific behavior associated with this "bundle" of attributes.  If yes, class, 
if no, nothing wrong with dictionary.

cheers,
Bill
On Feb 11, 2011, at 9:56 AM, Martin De Kauwe wrote:

> Hi,
> 
> I have a series of parameter values which i need to pass throughout my
> code (>100), in C I would use a structure for example. However in
> python it is not clear to me if it would be better to use a dictionary
> or build a class object? Personally I think accessing the values is
> neater (visually) with an object rather than a dictionary, e.g.
> 
> x = params['price_of_cats'] * params['price_of_elephants']
> 
> vs.
> 
> x = params.price_of_cats * params.price_of_elephants
> 
> So currently I am building a series of class objects to hold different
> parameters and then passing these through my code, e.g.
> 
> class EmptyObject:
>pass
> 
> self.animal_prices = EmptyObject()
> self.price_of_cats = 12 or reading a file and populating the object
> 
> 
> I would be keen to hear any reasons why this is a bad approach (if it
> is, I haven't managed to work this out)? Or perhaps there is a better
> one?
> 
> thanks
> 
> Martin
> -- 
> http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Python 32-bit on Windows 64-bit

2011-02-11 Thread Craig Yoshida
what kind of memory limitations to processes running on 32-bit python (with 
32-bit C extensions like scipy) have on 64-bit Windows?   I'm having occasional 
MemoryErrors when running a python program on 64-bit Windows 7 that runs fine 
on my OS X machine.  Both machines are using a 64-bit OS and have 4GB of RAM.

Thanks,
-Craig 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Ethan Furman

Andrea Crotti wrote:

On Feb 11, 3:56 pm, Martin De Kauwe  wrote:

Hi,

I have a series of parameter values which i need to pass throughout my
code (>100), in C I would use a structure for example. However in
python it is not clear to me if it would be better to use a dictionary
or build a class object? Personally I think accessing the values is
neater (visually) with an object rather than a dictionary, e.g.

x = params['price_of_cats'] * params['price_of_elephants']

vs.

x = params.price_of_cats * params.price_of_elephants


Visually neater is not really a good parameter to judge.


I strongly disagree.  Code readability is one of the most important issues.

~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reassign or discard Popen().stdout from a server process

2011-02-11 Thread Nobody
On Thu, 10 Feb 2011 08:35:24 +, John O'Hagan wrote:

>> > But I'm still a little curious as to why even unsuccessfully attempting
>> > to reassign stdout seems to stop the pipe buffer from filling up.
>> 
>> It doesn't. If the server continues to run, then it's ignoring/handling
>> both SIGPIPE and the EPIPE error. Either that, or another process has the
>> read end of the pipe open (so no SIGPIPE/EPIPE), and the server is using
>> non-blocking I/O or select() so that it doesn't block writing its
>> diagnostic messages.
> 
> The server fails with stdout=PIPE if I don't keep reading it, but
> doesn't fail if I do stdout=anything (I've tried files, strings,
> integers, and None) soon after starting the process, without any other
> changes. How is that consistent with either of the above conditions? I'm
> sure you're right, I just don't understand.

What do you mean by "fail". I wouldn't be surprised if it hung, due to the
write() on stdout blocking. If you reassign the .stdout member, the
existing file object is likely to become unreferenced, get garbage
collected, and close the pipe, which would prevent the server from
blocking (the write() will fail rather than blocking).

If the server puts the pipe into non-blocking mode, write() will fail with
EAGAIN if you don't read it but with EPIPE if you close the pipe. The
server may handle these cases differently.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Terry Reedy

or Module;-?

On 2/11/2011 9:56 AM, Martin De Kauwe wrote:

Hi,

I have a series of parameter values which i need to pass throughout my
code (>100), in C I would use a structure for example. However in
python it is not clear to me if it would be better to use a dictionary
or build a class object? Personally I think accessing the values is
neater (visually) with an object rather than a dictionary, e.g.


Dicts are, of course objects. That said, if all keys are identifier 
strings, then attribute access is nicer. A module is essentially a dict 
with all identifier keys, accessed as attributes.


mod.a is mod.__dict__['a']

Module are sometimes regarded as singleton data-only classes.
Just put 'import params' in every file that needs to read or write them.
The stdlib has at least a few modules that consist only of constants.
One example is tkinter.constants.

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Andrea Crotti

Il giorno 11/feb/2011, alle ore 17.01, Martin De Kauwe ha scritto:
> 
> i have a number some are smaller, for example switch/control flags.
> But the rest can be quite large. I can split them but I don't see the
> advantage particularly. Currently by using them (e.g.
> params.rate_of_decomp) it clearly distinguishes in the code this was a
> model parameter read in from a file. I could create more categories
> but it just means more names to remember and change in the code.

Well if you read those parameters from a file, I guess it's an INI file.
Then if you use configobj you get already a class which can be converted to a 
dict easily.

You can even validate the input to make sure you're not getting out of range 
values.
I always use ini files whenever I can configure something externally, and it 
works pretty well.

Does that help?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shared memory python between two separate shell-launched processes

2011-02-11 Thread Miki Tebeka
> So speed up the compile-test cycle I'm thinking about running a
> completely separate process (not a fork, but a processed launched form
> a different terminal) that can load the cache once then dunk it in an
> area of shareed memory.Each time I debug the main program, it can
> start up quickly and read from the shared memory instead of loading
> the cache itself.
You can fork and set "hard" breakpoint using "import pdb; pdb.set_trace()". Not 
sure how Emacs will handle that but you can use pdb from the terminal. For easy 
forking see http://pythonwise.blogspot.com/2009/04/pmap.html :)

Another option to try is maybe mmap the file?

HTH,
--
Miki
http://pythonwise.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Dan Stromberg
On Fri, Feb 11, 2011 at 6:56 AM, Martin De Kauwe  wrote:
> Hi,
>
> I have a series of parameter values which i need to pass throughout my
> code (>100), in C I would use a structure for example. However in
> python it is not clear to me if it would be better to use a dictionary
> or build a class object? Personally I think accessing the values is
> neater (visually) with an object rather than a dictionary, e.g.
>
> x = params['price_of_cats'] * params['price_of_elephants']
>
> vs.
>
> x = params.price_of_cats * params.price_of_elephants
>
> So currently I am building a series of class objects to hold different
> parameters and then passing these through my code, e.g.
>
> class EmptyObject:
>    pass
>
> self.animal_prices = EmptyObject()
> self.price_of_cats = 12 or reading a file and populating the object
>
>
> I would be keen to hear any reasons why this is a bad approach (if it
> is, I haven't managed to work this out)? Or perhaps there is a better
> one?

I'd use a class rather than a dictionary - because with a class,
pylint (and perhaps PyChecker and pyflakes?) should be able to detect
typos upfront.  With a dictionary, typos remain runtime timebombs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which non SQL Database ?

2011-02-11 Thread Doug Epling

On 12/4/2010 5:42 PM, Jorge Biquez wrote:

Hello all.

Newbie question. Sorry.

As part of my process to learn python I am working on two personal
applications. Both will do it fine with a simple structure of data
stored in files. I now there are lot of databases around I can use but I
would like to know yoor advice on what other options you would consider
for the job (it is training so no pressure on performance). One
application will run as a desktop one,under Windows, Linux, Macintosh,
being able to update data, not much, not complex, not many records. The
second application, running behind web pages, will do the same, I mean,
process simple data, updating showing data. not much info, not complex.


So, why not LDAP?


As an excersice it is more than enough I guess and will let me learn
what I need for now.
Talking with a friend about what he will do (he use C only) he suggest
to take a look on dBase format file since it is a stable format, fast
and the index structure will be fine or maybe go with BD (Berkley)
database file format (I hope I understood this one correctly) . Plain
files it is not an option since I would like to have option to do rapid
searches.

What would do you suggest to take a look? If possible available under
the 3 plattforms.

Thanks in advance for your comments.

Jorge Biquez



--
http://mail.python.org/mailman/listinfo/python-list


Re: Asterisk sign before the 'self' keyword

2011-02-11 Thread christian.posta
On Feb 11, 9:57 am, "christian.posta" 
wrote:
> On Feb 11, 9:10 am, Robert Kern  wrote:
>
>
>
> > On 2/11/11 9:06 AM, christian.posta wrote:
>
> > > I searched quickly to see whether this may have been discussed before,
> > > but it's possible my search criteria was not refined enough to get any
> > > hits. Forgive me if this is a silly question..
>
> > > I was reading some Python code from a third-party app for the django
> > > project... i saw this in the code and I wasn't certain what it means,
> > > nor could I find anything helpful from google.
>
> > > Within the __call__ function for a class, I saw a method of that class
> > > referred to like this:
>
> > > *self.()
>
> > > The brackets indicate the method name.
> > > What does the *self refer to??
> > > Does it somehow indicate the scope of the 'self' variable?
>
> > Can you show the whole statement? Most likely, this was embedded in some 
> > other
> > call, e.g.:
>
> >    foo(*self.method())
>
> > If this is the case, the * does not bind to "self"; it binds to all of
> > (self.method()), i.e.:
>
> >    foo(*(self.method()))
>
> > This is just the foo(*args) syntax that unpacks a tuple into individual
> > arguments to pass to foo().
>
> >http://docs.python.org/tutorial/controlflow.html#unpacking-argument-l...
>
> > --
> > Robert Kern
>
> > "I have come to believe that the whole world is an enigma, a harmless enigma
> >   that is made terrible by our own mad attempt to interpret it as though it 
> > had
> >   an underlying truth."
> >    -- Umberto Eco
>
> Yep, you are correct!
> It is indeed part of a larger statement. Sorry for the confusion.
>
> Here is the entire snippet:
>
>     def get_urls(self):
>         # In Django 1.1 and later you can hook this in to your urlconf
>         from django.conf.urls.defaults import patterns
>         return patterns('', *self.get_urlpatterns())

Thank you both Ian and Robert. It now makes perfect sense!

Thanks!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asterisk sign before the 'self' keyword

2011-02-11 Thread christian.posta
On Feb 11, 9:10 am, Robert Kern  wrote:
> On 2/11/11 9:06 AM, christian.posta wrote:
>
>
>
> > I searched quickly to see whether this may have been discussed before,
> > but it's possible my search criteria was not refined enough to get any
> > hits. Forgive me if this is a silly question..
>
> > I was reading some Python code from a third-party app for the django
> > project... i saw this in the code and I wasn't certain what it means,
> > nor could I find anything helpful from google.
>
> > Within the __call__ function for a class, I saw a method of that class
> > referred to like this:
>
> > *self.()
>
> > The brackets indicate the method name.
> > What does the *self refer to??
> > Does it somehow indicate the scope of the 'self' variable?
>
> Can you show the whole statement? Most likely, this was embedded in some other
> call, e.g.:
>
>    foo(*self.method())
>
> If this is the case, the * does not bind to "self"; it binds to all of
> (self.method()), i.e.:
>
>    foo(*(self.method()))
>
> This is just the foo(*args) syntax that unpacks a tuple into individual
> arguments to pass to foo().
>
> http://docs.python.org/tutorial/controlflow.html#unpacking-argument-l...
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it 
> had
>   an underlying truth."
>    -- Umberto Eco

Yep, you are correct!
It is indeed part of a larger statement. Sorry for the confusion.

Here is the entire snippet:

def get_urls(self):
# In Django 1.1 and later you can hook this in to your urlconf
from django.conf.urls.defaults import patterns
return patterns('', *self.get_urlpatterns())
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asterisk sign before the 'self' keyword

2011-02-11 Thread christian.posta
On Feb 11, 9:10 am, Robert Kern  wrote:
> On 2/11/11 9:06 AM, christian.posta wrote:
>
>
>
> > I searched quickly to see whether this may have been discussed before,
> > but it's possible my search criteria was not refined enough to get any
> > hits. Forgive me if this is a silly question..
>
> > I was reading some Python code from a third-party app for the django
> > project... i saw this in the code and I wasn't certain what it means,
> > nor could I find anything helpful from google.
>
> > Within the __call__ function for a class, I saw a method of that class
> > referred to like this:
>
> > *self.()
>
> > The brackets indicate the method name.
> > What does the *self refer to??
> > Does it somehow indicate the scope of the 'self' variable?
>
> Can you show the whole statement? Most likely, this was embedded in some other
> call, e.g.:
>
>    foo(*self.method())
>
> If this is the case, the * does not bind to "self"; it binds to all of
> (self.method()), i.e.:
>
>    foo(*(self.method()))
>
> This is just the foo(*args) syntax that unpacks a tuple into individual
> arguments to pass to foo().
>
> http://docs.python.org/tutorial/controlflow.html#unpacking-argument-l...
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it 
> had
>   an underlying truth."
>    -- Umberto Eco

Yep, you are correct!
It is indeed part of a larger statement. Sorry for the confusion.

Here is the entire snippet:

def get_urls(self):
# In Django 1.1 and later you can hook this in to your urlconf
from django.conf.urls.defaults import patterns
return patterns('', *self.get_urlpatterns())
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asterisk sign before the 'self' keyword

2011-02-11 Thread christian.posta
On Feb 11, 9:10 am, Robert Kern  wrote:
> On 2/11/11 9:06 AM, christian.posta wrote:
>
>
>
> > I searched quickly to see whether this may have been discussed before,
> > but it's possible my search criteria was not refined enough to get any
> > hits. Forgive me if this is a silly question..
>
> > I was reading some Python code from a third-party app for the django
> > project... i saw this in the code and I wasn't certain what it means,
> > nor could I find anything helpful from google.
>
> > Within the __call__ function for a class, I saw a method of that class
> > referred to like this:
>
> > *self.()
>
> > The brackets indicate the method name.
> > What does the *self refer to??
> > Does it somehow indicate the scope of the 'self' variable?
>
> Can you show the whole statement? Most likely, this was embedded in some other
> call, e.g.:
>
>    foo(*self.method())
>
> If this is the case, the * does not bind to "self"; it binds to all of
> (self.method()), i.e.:
>
>    foo(*(self.method()))
>
> This is just the foo(*args) syntax that unpacks a tuple into individual
> arguments to pass to foo().
>
> http://docs.python.org/tutorial/controlflow.html#unpacking-argument-l...
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it 
> had
>   an underlying truth."
>    -- Umberto Eco

Yep, you are correct!
It is indeed part of a larger statement. Sorry for the confusion.

Here is the entire snippet:

def get_urls(self):
# In Django 1.1 and later you can hook this in to your urlconf
from django.conf.urls.defaults import patterns
return patterns('', *self.get_urlpatterns())
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which non SQL Database ?

2011-02-11 Thread Aahz
In article <4d3c8d53$0$44021$742ec...@news.sonic.net>,
John Nagle   wrote:
>
> Google's BigTable and Facebook's Cassandra offer impressive
>performance at very large scale.  But they're way overkill for
>a desktop app.  Even the midrange systems, like CouchDB, are
>far too much machinery for a desktop app.

Side note: one reason we chose Cassandra for our "midrange" requirements
was that it doesn't have master nodes, and we wanted to avoid single
point of failure.

Side note 2: do NOT run Cassandra on a virtual machine.  That was a bad
mistake we made because our performance requirements are fairly modest.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Programming language design is not a rational science. Most reasoning
about it is at best rationalization of gut feelings, and at worst plain
wrong."  --GvR, python-ideas, 2009-03-01
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shared memory python between two separate shell-launched processes

2011-02-11 Thread Philip
On Feb 11, 6:27 am, Adam Skutt  wrote:
> On Feb 10, 9:30 am, "Charles Fox (Sheffield)" 
> wrote:
>
> > But when I look at posix_ipc and POSH it looks like you have to fork
> > the second process from the first one, rather than access the shared
> > memory though a key ID as in standard C unix shared memory.  Am I
> > missing something?   Are there any other ways to do this?
>
> I don't see what would have given you that impression at all, at least
> with posix_ipc.  It's a straight wrapper on the POSIX shared memory
> functions, which can be used across processes when used correctly.
> Even if for some reason that implementation lacks the right stuff,
> there's always SysV IPC.
>
[some stuff snipped]
> Also, just FYI, there is no such thing as "standard C unix shared
> memory".  There are at least three different relatively widely-
> supported techniques: SysV, (anonymous) mmap, and POSIX Realtime
> Shared Memory (which normally involves mmap).  All three are
> standardized by the Open Group, and none of the three are implemented
> with perfect consistency across Unicies.

Adam is 100% correct. posix_ipc doesn't require fork.

@the OP: Charles, since you refer to "standard" shared memory as being
referred to by a key, it sounds like you're thinking of SysV shared
memory. POSIX IPC objects are referred to by a string that looks like
a filename, e.g. "/my_shared_memory".

Note that there's a module called sysv_ipc which is a close cousin of
posix_ipc. I'm the author of both. IMO POSIX is easier to use.

Cheers
Philip


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to Write grep in Emacs Lisp (tutorial)

2011-02-11 Thread Xah Lee
On Feb 11, 2:06 am, Alexander Gattin  wrote:
> Hello,
>
> On Tue, Feb 08, 2011 at 05:32:05PM +, Icarus
>
> Sparry wrote:
> > The key thing which makes this 'modern' is the
> > '+' at the end of the command, rather than '\;'.
> > This causes find to execute the grep once per
> > group of files, rather than once per file.
>
> many thanks to you, man!
>
> I'm surprised to find out that this works on HP-UX
> B.11.31 and SunOS 5.9 (but not on HP Tru64 UNIX
> V5.1B).

Is HP-UX still alive?

lol. in 2000 i ported our ecommerce web app from Solaris to it. Am not
exactly thrilled. At the time, i vaguely recall, the HP sales guys
come to us and tells us they have this heart-beat technology ...

 Xah
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asterisk sign before the 'self' keyword

2011-02-11 Thread Robert Kern

On 2/11/11 9:06 AM, christian.posta wrote:

I searched quickly to see whether this may have been discussed before,
but it's possible my search criteria was not refined enough to get any
hits. Forgive me if this is a silly question..

I was reading some Python code from a third-party app for the django
project... i saw this in the code and I wasn't certain what it means,
nor could I find anything helpful from google.

Within the __call__ function for a class, I saw a method of that class
referred to like this:

*self.()

The brackets indicate the method name.
What does the *self refer to??
Does it somehow indicate the scope of the 'self' variable?


Can you show the whole statement? Most likely, this was embedded in some other 
call, e.g.:


  foo(*self.method())

If this is the case, the * does not bind to "self"; it binds to all of 
(self.method()), i.e.:


  foo(*(self.method()))

This is just the foo(*args) syntax that unpacks a tuple into individual 
arguments to pass to foo().


http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

--
http://mail.python.org/mailman/listinfo/python-list


TestFixtures 1.9.0 Released!

2011-02-11 Thread Chris Withers

Hi All,

I'm happy to announce a new release of TestFixtures.

This release adds a helper for tests of code using zope.component:

http://packages.python.org/testfixtures/components.html

The package is on PyPI and a full list of all the links to docs, issue 
trackers and the like can be found here:


http://www.simplistix.co.uk/software/python/testfixtures

cheers,

Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Martin De Kauwe
On Feb 12, 2:40 am, Andrea Crotti  wrote:
> On Feb 11, 3:56 pm, Martin De Kauwe  wrote:
>
> > Hi,
>
> > I have a series of parameter values which i need to pass throughout my
> > code (>100), in C I would use a structure for example. However in
> > python it is not clear to me if it would be better to use a dictionary
> > or build a class object? Personally I think accessing the values is
> > neater (visually) with an object rather than a dictionary, e.g.
>
> > x = params['price_of_cats'] * params['price_of_elephants']
>
> > vs.
>
> > x = params.price_of_cats * params.price_of_elephants
>
> Visually neater is not really a good parameter to judge.

Yes and No. Makes the code easier to read and less picky to type out,
in my opinion! But regarding the "no" that is why I posted the
question

> And in a class you can also overload __getattr__ to get the same
> syntax as a dictionary.
> But (>100) parameters seems really a lot, are you sure you can't split
> in many classes instead?

i have a number some are smaller, for example switch/control flags.
But the rest can be quite large. I can split them but I don't see the
advantage particularly. Currently by using them (e.g.
params.rate_of_decomp) it clearly distinguishes in the code this was a
model parameter read in from a file. I could create more categories
but it just means more names to remember and change in the code.

>
> Classes have also the advantage that you can do many things behind the
> scenes, while with plain dictionaries you can't do much...
> Where do you take those parameters from and what are they used for?

I have a big model which calculates a process, but this is made up of
a number of smaller models. I have coded each of these are separate
classes which expect to receive an object e.g. params, or two objects
e.g. params and switches.

thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asterisk sign before the 'self' keyword

2011-02-11 Thread Ian Kelly

On 2/11/2011 8:06 AM, christian.posta wrote:

I searched quickly to see whether this may have been discussed before,
but it's possible my search criteria was not refined enough to get any
hits. Forgive me if this is a silly question..

I was reading some Python code from a third-party app for the django
project... i saw this in the code and I wasn't certain what it means,
nor could I find anything helpful from google.

Within the __call__ function for a class, I saw a method of that class
referred to like this:

*self.()

The brackets indicate the method name.
What does the *self refer to??
Does it somehow indicate the scope of the 'self' variable?
Thanks in advance...


If the line appeared exactly as you have it here, then it would be a 
syntax error.  More likely is that you saw something like this:


self.do_something(*self.return_a_sequence())

Here, "return_a_sequence" could return any sequence or iterable.  The * 
indicates that whatever follows it is to be unpacked and passed into 
"do_something" as a series of individual arguments.  For example, if 
"return_a_sequence" returns the tuple (1, 2, 3), then the above would be 
functionally equivalent to:


self.do_somethign(1, 2, 3)

--
http://mail.python.org/mailman/listinfo/python-list


Re: Class or Dictionary?

2011-02-11 Thread Andrea Crotti
On Feb 11, 3:56 pm, Martin De Kauwe  wrote:
> Hi,
>
> I have a series of parameter values which i need to pass throughout my
> code (>100), in C I would use a structure for example. However in
> python it is not clear to me if it would be better to use a dictionary
> or build a class object? Personally I think accessing the values is
> neater (visually) with an object rather than a dictionary, e.g.
>
> x = params['price_of_cats'] * params['price_of_elephants']
>
> vs.
>
> x = params.price_of_cats * params.price_of_elephants

Visually neater is not really a good parameter to judge.
And in a class you can also overload __getattr__ to get the same
syntax as a dictionary.
But (>100) parameters seems really a lot, are you sure you can't split
in many classes instead?

Classes have also the advantage that you can do many things behind the
scenes, while with plain dictionaries you can't do much...
Where do you take those parameters from and what are they used for?
-- 
http://mail.python.org/mailman/listinfo/python-list


Asterisk sign before the 'self' keyword

2011-02-11 Thread christian.posta
I searched quickly to see whether this may have been discussed before,
but it's possible my search criteria was not refined enough to get any
hits. Forgive me if this is a silly question..

I was reading some Python code from a third-party app for the django
project... i saw this in the code and I wasn't certain what it means,
nor could I find anything helpful from google.

Within the __call__ function for a class, I saw a method of that class
referred to like this:

*self.()

The brackets indicate the method name.
What does the *self refer to??
Does it somehow indicate the scope of the 'self' variable?
Thanks in advance...


-- 
http://mail.python.org/mailman/listinfo/python-list


Class or Dictionary?

2011-02-11 Thread Martin De Kauwe
Hi,

I have a series of parameter values which i need to pass throughout my
code (>100), in C I would use a structure for example. However in
python it is not clear to me if it would be better to use a dictionary
or build a class object? Personally I think accessing the values is
neater (visually) with an object rather than a dictionary, e.g.

x = params['price_of_cats'] * params['price_of_elephants']

vs.

x = params.price_of_cats * params.price_of_elephants

So currently I am building a series of class objects to hold different
parameters and then passing these through my code, e.g.

class EmptyObject:
pass

self.animal_prices = EmptyObject()
self.price_of_cats = 12 or reading a file and populating the object


I would be keen to hear any reasons why this is a bad approach (if it
is, I haven't managed to work this out)? Or perhaps there is a better
one?

thanks

Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: returning all matching groups with re.search()

2011-02-11 Thread MRAB

On 11/02/2011 04:34, Roland Mueller wrote:

Hello,

On 02/07/2011 06:26 PM, Mauro Caceres wrote:

>>> import re
>>> help(re.findall)
Help on function findall in module re:

findall(pattern, string, flags=0)
Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result.

>>> re.findall('e','fredbarneybettywilma')
['e', 'e', 'e']


depending on what is intended the non-overlapping behaviour of findall()
may cause some problem:

 >>> re.findall('.[aeiou].','fredbarneybettywilma')
['red', 'bar', 'ney', 'bet', 'wil']

 >>> re.findall('.[aeiouy].','fredbarneybettywilma')
['red', 'bar', 'ney', 'bet', 'tyw']


Overlapping matches are supported by this regex module:

http://pypi.python.org/pypi/regex
--
http://mail.python.org/mailman/listinfo/python-list


Re: Executing functions

2011-02-11 Thread Ethan Furman

DataSmash wrote:

Can someone help me understand why Example #1 & Example #2 will run
the functions,
while Example #3 DOES NOT?
Thanks for your time!
R.D.

def One():
print "running fuction 1"
def Two():
print "running fuction 2"
def Three():
print "running fuction 3"


# Example #1
fList = ["Two()","Three()"]
for func in fList:
exec func


In this case, func is set to the strings 'Two()' and 'Three()', then the 
 line tells Python to evaluate the strings and execute them. 
 While this style can be useful, it is also *much* slower than example 
2; if all you want is to cycle through the functions, a better way is:


--> fList = [Two, Three]
--> for func in fList:
--> func()



# Example #2
Two()
Three()


The functions Two and Three are called directly



# Example #2 <-- should be 3  :)
fList = ["Two()","Three()"]
for func in fList:
func


This is not calling func (no () at the end), and in fact doesn't do 
anything if called as a script besides evaluate func -- it's a string, 
but not being assigned anywhere, so unless you are running from the 
interactive prompt where it will be echoed to screen, nothing happens.


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parameterized functions of no arguments?

2011-02-11 Thread Hrvoje Niksic
Chris Rebert  writes:

> It's a well-known problem due to the intricacies of Python's scoping
> rules.

Actually, it is not specific to Python's scoping rules (which mandate
local, then module-level, then built-in name lookup).  The root of the
surprise is, as you correctly point out, the fact that the variable's
"cell" is shared by all iterations through the loop.  Taking that into
account, it logically follows that all enclosed functions end up reading
the same value.

This is not endemic to Python, the exact same surprise is present in
Common Lisp, a language with long tradition of closures and otherwise
radically different scoping rules.

* (setq l (loop for i from 1 to 10 collect (lambda () i)))
* (mapcar #'funcall l)
(11 11 11 11 11 11 11 11 11 11)
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Executing functions

2011-02-11 Thread Andreas Tawn
> Can someone help me understand why Example #1 & Example #2 will run
> the functions,
> while Example #3 DOES NOT?
> Thanks for your time!
> R.D.
> 
> def One():
> print "running fuction 1"
> def Two():
> print "running fuction 2"
> def Three():
> print "running fuction 3"
> 
> 
> # Example #1
> fList = ["Two()","Three()"]
> for func in fList:
> exec func
> 
> # Example #2
> Two()
> Three()
> 
> # Example #3
> fList = ["Two()","Three()"]
> for func in fList:
> func

In example 3, func is a string literal not a function object.

Example 1 works because the exec statement parses and then evaluates the func 
string resulting in the two function calls you see.

Try this instead...

fList = [One, Two, Three]
for func in fList:
func()

Cheers,

Drea
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing functions

2011-02-11 Thread nn
On Feb 11, 9:15 am, DataSmash  wrote:
> Can someone help me understand why Example #1 & Example #2 will run
> the functions,
> while Example #3 DOES NOT?
> Thanks for your time!
> R.D.
>
> def One():
>     print "running fuction 1"
> def Two():
>     print "running fuction 2"
> def Three():
>     print "running fuction 3"
>
> # Example #1
> fList = ["Two()","Three()"]
> for func in fList:
>     exec func
>
> # Example #2
> Two()
> Three()
>
> # Example #2
> fList = ["Two()","Three()"]
> for func in fList:
>     func

Example 1 is executing the code inside strings
Example 2 is evaluating two functions and throwing the result away
Example 3 is evaluating literals and throwing the result away

I don't know why you would expect the third example to run the
functions.
Maybe running this version will enlighten you:

fList = ["random","stuff"]
for func in fList:
func

-- 
http://mail.python.org/mailman/listinfo/python-list


Executing functions

2011-02-11 Thread DataSmash
Can someone help me understand why Example #1 & Example #2 will run
the functions,
while Example #3 DOES NOT?
Thanks for your time!
R.D.

def One():
print "running fuction 1"
def Two():
print "running fuction 2"
def Three():
print "running fuction 3"


# Example #1
fList = ["Two()","Three()"]
for func in fList:
exec func

# Example #2
Two()
Three()

# Example #2
fList = ["Two()","Three()"]
for func in fList:
func
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wx.Frame hidden, and customising the close button

2011-02-11 Thread Mark Carter
On Feb 11, 1:39 pm, Vlastimil Brom  wrote:
> (wxPython-specific questions may be rather discussed  on that 
> maillist:http://groups.google.com/group/wxpython-users/topics?pli=1

Just the ticket! Many thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wx.Frame hidden, and customising the close button

2011-02-11 Thread Vlastimil Brom
2011/2/11 Mark Carter :
> Is there a way of testing whether a frame (suppose I have it as a
> variable my_frame) is hidden in wxPython?
>
> Also, is there a way that I can over-ride the close button so that the
> frame becomes hidden rather than destroyed, and perform supplementary
> tests?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
Hi,
For testing whether the frame is shown, you can simply use frm.IsShown()
>>> my_frame.IsShown()
True
>>>

[here shown with a shell connected to that frame]

To intercept closing the window using a clicks on the "x icon" catch
the respective event
wx.EVT_CLOSE

Check the sample e.g. in
http://wiki.wxpython.org/wxPython%20by%20Example
"Adding an Event Handler"

(wxPython-specific questions may be rather discussed  on that maillist:
http://groups.google.com/group/wxpython-users/topics?pli=1

wxpython-us...@googlegroups.com )

hth,
  vbr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with giant font sizes in tkinter

2011-02-11 Thread Arndt Roger Schneider

Steven D'Aprano schrieb:

On Thu, 10 Feb 2011 15:48:47 +, Cousin Stanley wrote:



Steven D'Aprano wrote:



I have a tkinter application under Python 2.6 which is shows text in a
giant font, about twenty(?) times larger than expected.

The fonts are set using:

titlefont = '-Adobe-Helvetica-Bold-R-Normal-*-180-*' 
buttonfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*' 
labelfont = '-Adobe-Helvetica-Bold-R-Normal-*-140-*' 



 Although I've been a linux user for several years, that type of font
 spec hurts my head  :-)

 Will the more simplistic type of tuple spec not work in your tkinter
 application ?



I don't know, but I'll give it a try.

Nevertheless, I'd like to learn how to diagnose these sorts of font 
issues. Can anyone suggest where I should start?






Those adobe helveticas are bitmap fonts.
Tk 8.5 uses freetype to render fonts under X11,
if you wish to use outdated bitmap fonts under X11,
then disable-xft when building Tk 8.5.

I do assume there are different tk versions on your
various platforms, and the troubling one is with
version 8.5 --8.5 uses anti-aliasing hence freetype.

Recommendation: Get rid of bitmap fonts under X11.

BTW the default fonts under Linux are:
bitstream vera sans (for helvetica)
bitstream vera (for times)
and bitstream vera sans mono (for courier).

In my opion those bitstream fonts are much better
than the mentioned Adobe fonts.

-roger




--
http://mail.python.org/mailman/listinfo/python-list


Re: Shared memory python between two separate shell-launched processes

2011-02-11 Thread Jean-Paul Calderone
On Feb 11, 5:52 am, "Charles Fox (Sheffield)" 
wrote:
> On Feb 10, 6:22 pm, Jean-Paul Calderone 
> wrote:
>
>
>
>
>
>
>
>
>
> > On Feb 10, 12:21 pm, "Charles Fox (Sheffield)" 
> > wrote:
>
> > > On Feb 10, 3:43 pm, Jean-Paul Calderone 
> > > wrote:
>
> > > > On Feb 10, 9:30 am, "Charles Fox (Sheffield)" 
> > > > wrote:
>
> > > > > Hi guys,
> > > > > I'm working on debugging a large python simulation which begins by
> > > > > preloading a huge cache of data.  I want to step through code on many
> > > > > runs to do the debugging.   Problem is that it takes 20 seconds to
> > > > > load the cache at each launch.  (Cache is a dict in a 200Mb cPickle
> > > > > binary file).
>
> > > > > So speed up the compile-test cycle I'm thinking about running a
> > > > > completely separate process (not a fork, but a processed launched form
> > > > > a different terminal)
>
> > > > Why _not_ fork?  Load up your data, then go into a loop forking and
> > > > loading/
> > > > running the rest of your code in the child.  This should be really
> > > > easy to
> > > > implement compared to doing something with shared memory, and solves
> > > > the
> > > > problem you're trying to solve of long startup time just as well.  It
> > > > also
> > > > protects you from possible bugs where the data gets corrupted by the
> > > > code
> > > > that operates on it, since there's only one copy shared amongst all
> > > > your
> > > > tests.  Is there some other benefit that the shared memory approach
> > > > gives
> > > > you?
>
> > > > Of course, adding unit tests that exercise your code on a smaller data
> > > > set
> > > > might also be a way to speed up development.
>
> > > > Jean-Paul
>
> > > Thanks Jean-Paul, I'll have a think about this.  I'm not sure if it
> > > will get me exactly what I want though, as I would need to keep
> > > unloading my development module and reloading it, all within the
> > > forked process, and I don't see how my debugger (and emacs pdb
> > > tracking) will keep up with that to let me step though the code.
>
> > Not really.  Don't load your code at all in the parent.  Then there's
> > nothing to unload in each child process, just some code to load for
> > the very first time ever (as far as that process is concerned).
>
> > Jean-Paul
>
> Jean, sorry I'm still not sure what you mean, could you give a couple
> of lines of pseudocode to illustrate it?   And explain how my emacs
> pdbtrack would still be able to pick it up?
> thanks,
> charles

import os
import loader
data = loader.preload()

while True:
pid = os.fork()
if pid == 0:
import program
program.main(data)
else:
os.waitpid(pid, 0)

But I won't actually try to predict how this is going to interact with
emacs pdbtrack.

Jean-Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


wx.Frame hidden, and customising the close button

2011-02-11 Thread Mark Carter
Is there a way of testing whether a frame (suppose I have it as a
variable my_frame) is hidden in wxPython?

Also, is there a way that I can over-ride the close button so that the
frame becomes hidden rather than destroyed, and perform supplementary
tests?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Remove whitespaces and line breaks in a XML file

2011-02-11 Thread Sven

On 2011-02-07 18:46:17 -0500, Josh English said:

I found the code posted at 


http://infix.se/2007/02/06/gentlemen-indent-your-xml

quite helpful in turning my xml into human-readable structures. It works
best for XML-Data.


lxml, which the code is using, already has a pretty_print feature 
according to this http://codespeak.net/lxml/tutorial.html which would 
do the same, would it not?


--
./Sven-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shared memory python between two separate shell-launched processes

2011-02-11 Thread Adam Skutt
On Feb 10, 9:30 am, "Charles Fox (Sheffield)" 
wrote:
>
> But when I look at posix_ipc and POSH it looks like you have to fork
> the second process from the first one, rather than access the shared
> memory though a key ID as in standard C unix shared memory.  Am I
> missing something?   Are there any other ways to do this?
>

I don't see what would have given you that impression at all, at least
with posix_ipc.  It's a straight wrapper on the POSIX shared memory
functions, which can be used across processes when used correctly.
Even if for some reason that implementation lacks the right stuff,
there's always SysV IPC.

Open the same segment in both processes, use mmap, and go.  What will
be tricky, of course, is binding to wherever you stuffed the
dictionary.  I think ctypes.cast() can do what you need, but I've
never done it before.

Also, just FYI, there is no such thing as "standard C unix shared
memory".  There are at least three different relatively widely-
supported techniques: SysV, (anonymous) mmap, and POSIX Realtime
Shared Memory (which normally involves mmap).  All three are
standardized by the Open Group, and none of the three are implemented
with perfect consistency across Unicies.

Adam
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shared memory python between two separate shell-launched processes

2011-02-11 Thread Charles Fox (Sheffield)
On Feb 10, 6:22 pm, Jean-Paul Calderone 
wrote:
> On Feb 10, 12:21 pm, "Charles Fox (Sheffield)" 
> wrote:
>
>
>
> > On Feb 10, 3:43 pm, Jean-Paul Calderone 
> > wrote:
>
> > > On Feb 10, 9:30 am, "Charles Fox (Sheffield)" 
> > > wrote:
>
> > > > Hi guys,
> > > > I'm working on debugging a large python simulation which begins by
> > > > preloading a huge cache of data.  I want to step through code on many
> > > > runs to do the debugging.   Problem is that it takes 20 seconds to
> > > > load the cache at each launch.  (Cache is a dict in a 200Mb cPickle
> > > > binary file).
>
> > > > So speed up the compile-test cycle I'm thinking about running a
> > > > completely separate process (not a fork, but a processed launched form
> > > > a different terminal)
>
> > > Why _not_ fork?  Load up your data, then go into a loop forking and
> > > loading/
> > > running the rest of your code in the child.  This should be really
> > > easy to
> > > implement compared to doing something with shared memory, and solves
> > > the
> > > problem you're trying to solve of long startup time just as well.  It
> > > also
> > > protects you from possible bugs where the data gets corrupted by the
> > > code
> > > that operates on it, since there's only one copy shared amongst all
> > > your
> > > tests.  Is there some other benefit that the shared memory approach
> > > gives
> > > you?
>
> > > Of course, adding unit tests that exercise your code on a smaller data
> > > set
> > > might also be a way to speed up development.
>
> > > Jean-Paul
>
> > Thanks Jean-Paul, I'll have a think about this.  I'm not sure if it
> > will get me exactly what I want though, as I would need to keep
> > unloading my development module and reloading it, all within the
> > forked process, and I don't see how my debugger (and emacs pdb
> > tracking) will keep up with that to let me step though the code.
>
> Not really.  Don't load your code at all in the parent.  Then there's
> nothing to unload in each child process, just some code to load for
> the very first time ever (as far as that process is concerned).
>
> Jean-Paul


Jean, sorry I'm still not sure what you mean, could you give a couple
of lines of pseudocode to illustrate it?   And explain how my emacs
pdbtrack would still be able to pick it up?
thanks,
charles

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parameterized functions of no arguments?

2011-02-11 Thread Rotwang

On 11/02/2011 08:19, Steven D'Aprano wrote:


[...]

Re-writing them as normal function defs may help. I'm going to do them in
reverse order:

# lambda: f(k)
def func():
 return f(k)

When you call func() with no arguments, the body is executed and f(k) is
returned. Where do f and k come from? At runtime, Python searches the
local namespace of func(), and doesn't find either f or k. It then
searches the non-local namespace, that is, the function or method that
surrounds func (or your lambda), if any. In your case, there is no such
nested function, so finally it searches the global namespace, and finds
both f and k. But by the time the function is called, the for-loop which
sets k has reached the end, and k always has the same value.



# (lambda x: lambda: f(x))(k)
def func(x):
 def inner():
 return f(x)
 return inner


When you call func(k), it creates a nested function. That nested function
includes a "closure", which is a copy of the namespace of func at the
time it is called. This closure includes a variable "k".

That inner function is returned and saved as the callback function. When
you call that callback function, it executes inner(), and f(k) is
returned. Where do f and k come from? As normal, Python searches the
local namespace, and doesn't find them, but then it finds the variable k
in the closure, and *not* the global k that the earlier example would
find.

This example may help:

store = []
for k in range(3):
 fa = lambda: "k has the value %d" % k
 fb = (lambda x: lambda: "x has the value %d" % x)(k)
 print("fa inside the loop", fa())
 print("fb inside the loop", fb())
 store.append(fa)
 store.append(fb)

for func in store:
 print("func outside the loop", func())

del k

store[1]()  # one of the closures
store[0]()  # one of the non-closures




Hope this helps.


Indeed it does. Thanks, and likewise to everyone else who replied.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to Write grep in Emacs Lisp (tutorial)

2011-02-11 Thread Alexander Gattin
Hello,

On Tue, Feb 08, 2011 at 05:32:05PM +, Icarus
Sparry wrote:
> The key thing which makes this 'modern' is the
> '+' at the end of the command, rather than '\;'.
> This causes find to execute the grep once per
> group of files, rather than once per file.

many thanks to you, man!

I'm surprised to find out that this works on HP-UX
B.11.31 and SunOS 5.9 (but not on HP Tru64 UNIX
V5.1B).

-- 
With best regards,
xrgtn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to Write grep in Emacs Lisp (tutorial)

2011-02-11 Thread Alexander Gattin
Hello,

On Thu, Feb 10, 2011 at 07:52:34AM +0100, Petter
Gustad wrote:
> r...@rpw3.org (Rob Warnock) writes:
> > invocation was given only one arg!! IT FOUND
> > THE PATTERN, BUT DIDN'T TELL ME WHAT
> > !@^%!$@#@! FILE IT WAS IN!!  :-{
> 
> Sounds frustrating, but grep -H will always
> print the filename, even when given a single
> filename on the command line.

not on HP-UX, though. Not even with "export
UNIX_STD=2003"

P.S. "find ... -exec ... +" works there just fine.

-- 
With best regards,
xrgtn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parameterized functions of no arguments?

2011-02-11 Thread Ben Finney
Rotwang  writes:

> On 11/02/2011 05:42, Ben Finney wrote:
> > What part is inelegant to your eye?
>
> I guess the fact that it exploits the way Python evaluates default
> function arguments to achieve something other than what they were
> intended for.

I see. If that seems like an exploit, I can see why you think it's
inelegant.

> Still, I see that Chris suggested the same solution (thanks, Chris) so
> it clearly isn't something that's frowned upon.

Indeed, in this forum we go to tedious lengths to explain that this
behaviour is the case in Python, so code that depends on it may even be
encouraged :-)

-- 
 \  “He that loveth father or mother more than me is not worthy of |
  `\me: and he that loveth son or daughter more than me is not |
_o__)worthy of me.” —Jesus, as quoted in Matthew 10:37 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy function, please help.

2011-02-11 Thread Stephen Hansen
On 2/10/11 7:34 PM, alex23 wrote:
> rantingrick  wrote:
>> 1. When has 2 bytecode instructions EVER out weighed a solid
>> readability feature's incorporation into Python?
> 
> The original point was whether or not the code is identical, which
> Terry showed it was not.

Rick does not understand what "identical" means.

Its a complicated word.

"Same" and "exactly the same" and "equivalent" are all also terms of art
that are not fully comprehended.

Someone says that these two things are the same. Terry points out that
they are not, in fact, the same at all. He does not make a value
judgment on what is better or not better: or what is preferred or not
preferred. He simply points out: they are not the same.

Everyone else understands that something may be different from something
else, and yet in the end we prefer what is technically slower -- because
it is more readable.

Everyone else may understand that something may be different from
something else, and yet arguing that they are THE SAME is worthy of an
objection, because it is simply, factually, wrong.

Cue Rick selectively quoting and telling me what it is I'm saying (while
utterly proving his inability to read basic English), and righteous
indignation about how bad I am as one of the Evil Ones of python-list.
Doing... bad things. Badly.

Because, I, er, am, bad.

Bad.

BAD.

CUZ. RICK. SAYS. SO.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with giant font sizes in tkinter

2011-02-11 Thread Stephen Hansen
On 2/10/11 7:15 PM, rantingrick wrote:
> I am *seriously* ...blah

You are a child.

This is your second pointless response to this thread.

Part of me wants to say, stop behaving like a 13 year old; only you're
behaving worse then several 13 year olds I know. It would be an insult
to their maturity to compare you to them.

"Grow up" doesn't quite do it. You're usually a troll, everyone gets
that. Its all you do, troll here and there, but this is all worse then
even what you spew out usually.

It's just... kinda, sad.

You can't even manage a point anymore. It's kinda funny, really. You've
proven yourself incapable of supporting position after position in
actual argument-- so now you're just not even able to rant. Once upon a
time you would seize upon this and find some reason to rant about--
something, to call to arms the silent majority, to declare you the
spokesman for all that is holy and proper and good, none of which can be
found here.

Now.. this? Lol.

Time to change your name. You're no longer Ranting Rick.
Congratulations! You're now Blabbering Rick.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


parse html rendered by js

2011-02-11 Thread yanghq
hi,
I wanna get attribute value like href,src... in html.

for simple html page libxml2dom can help me parse it into dom, and
get what  I want;

but for some pages rendered by js, like:

document.write(
''+
  ''+
''+
''+
''+
''+
''+
''+
  ''+
  ''+
''+
''
)
how can I get the atrribute value of 'src', thank you for any help.

---
Confidentiality Notice: The information contained in this e-mail and any 
accompanying attachment(s) 
is intended only for the use of the intended recipient and may be confidential 
and/or privileged of 
Neusoft Corporation, its subsidiaries and/or its affiliates. If any reader of 
this communication is 
not the intended recipient, unauthorized use, forwarding, printing,  storing, 
disclosure or copying 
is strictly prohibited, and may be unlawful.If you have received this 
communication in error,please 
immediately notify the sender by return e-mail, and delete the original message 
and all copies from 
your system. Thank you. 
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Pyro 3.11 released

2011-02-11 Thread yanghq
hi,
I wanna get attribute value like href,src... in html.

for simple html page libxml2dom can help me parse it into dom, and
get what  I want;

but for some pages rendered by js, like:

document.write(
''+
  ''+
''+
''+
''+
''+
''+
''+
  ''+
  ''+
''+
''
)
how can I get the atrribute value of 'src', thank you for any help


---
Confidentiality Notice: The information contained in this e-mail and any 
accompanying attachment(s) 
is intended only for the use of the intended recipient and may be confidential 
and/or privileged of 
Neusoft Corporation, its subsidiaries and/or its affiliates. If any reader of 
this communication is 
not the intended recipient, unauthorized use, forwarding, printing,  storing, 
disclosure or copying 
is strictly prohibited, and may be unlawful.If you have received this 
communication in error,please 
immediately notify the sender by return e-mail, and delete the original message 
and all copies from 
your system. Thank you. 
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parameterized functions of no arguments?

2011-02-11 Thread Steven D'Aprano
On Fri, 11 Feb 2011 06:32:56 +, Rotwang wrote:

> I don't understand why this works. What is the difference between
> 
>  (lambda x: lambda: f(x))(k)
> 
> and
> 
>  lambda: f(k)
> 
> ?

Re-writing them as normal function defs may help. I'm going to do them in 
reverse order:

# lambda: f(k)
def func():
return f(k)

When you call func() with no arguments, the body is executed and f(k) is 
returned. Where do f and k come from? At runtime, Python searches the 
local namespace of func(), and doesn't find either f or k. It then 
searches the non-local namespace, that is, the function or method that 
surrounds func (or your lambda), if any. In your case, there is no such 
nested function, so finally it searches the global namespace, and finds 
both f and k. But by the time the function is called, the for-loop which 
sets k has reached the end, and k always has the same value.



# (lambda x: lambda: f(x))(k)
def func(x):
def inner():
return f(x)
return inner


When you call func(k), it creates a nested function. That nested function 
includes a "closure", which is a copy of the namespace of func at the 
time it is called. This closure includes a variable "k".

That inner function is returned and saved as the callback function. When 
you call that callback function, it executes inner(), and f(k) is 
returned. Where do f and k come from? As normal, Python searches the 
local namespace, and doesn't find them, but then it finds the variable k 
in the closure, and *not* the global k that the earlier example would 
find.

This example may help:

store = []
for k in range(3):
fa = lambda: "k has the value %d" % k
fb = (lambda x: lambda: "x has the value %d" % x)(k)
print("fa inside the loop", fa())
print("fb inside the loop", fb())
store.append(fa)
store.append(fb)

for func in store:
print("func outside the loop", func())

del k

store[1]()  # one of the closures
store[0]()  # one of the non-closures




Hope this helps.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parameterized functions of no arguments?

2011-02-11 Thread Paul Rubin
Dennis Lee Bieber  writes:
>>  menu.add_command(label = str(k), command = lambda: f(k))
>   I'm not sure, but what effect does
>   menu.add_command(label=str(k), command = lambda k=k: f(k))
> have on the processing.

In the first example, k is a free variable in the lambda, so it's
captured from the outer scope when the lambda is evaluated:

>>> k = 3
>>> a = lambda: k
>>> k = 5
>>> a()
5

In the second example, k is bound as an arg to the lambda when the
lambda runs, initialized to the default value supplied when the lambda
was created:

>>> k = 3
>>> a = lambda k=5: k
>>> a()
5

In the weird looking k=k syntax, the "=k" gets k from the outer scope,
and uses it as a default value for the function arg that is bound in the
function.  I.e. if k=3 then lambda k=k: ...  is like lambda k=3:...
-- 
http://mail.python.org/mailman/listinfo/python-list