Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-20 Thread Steven D'Aprano
On Tue, 20 Jan 2009 15:04:34 +1000, James Mills wrote:

> Having come from all kinda of programming backgrounds and paradigms you
> learn to see the value in Python and the kind of simplicity it has to
> offer.

Oh yes, it is liberating to say "I don't care if my method crashes 
(raises an exception), it's the caller's fault for messing with my class' 
internals, and he can deal with it". I'm not being sarcastic by the way. 
It really is liberating not to have to deal with unexpected input or 
broken pre-conditions. Just let the caller deal with it!




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


Re: function to find the modification date of the project

2009-01-20 Thread Steven D'Aprano
On Mon, 19 Jan 2009 20:22:55 -0700, Joe Strout wrote:

>> What if a curious user simple looks at a file with an editor and saves
>> it without change?
> 
> You can't do that, on the Mac at least...

Are you sure? That's a rather incredible claim. Surely you mean *some Mac 
editors* disable the Save command if the file hasn't been edited? Other 
editors may not, and POSIX command line tools certainly won't.

But that's a minor point.


> But really, this is NOT going to happen.  These users wouldn't even
> know how to open the app bundle to find the Python files.

Ah, the sorts of users who say "I looked in the system folder, and there 
was nothing there, so I deleted it". I know them well :-)


> Any comments on the functioning and platform-independence of the code?


I've developed a taste for writing that sort of function as a series of 
iterators. That's much like the Unix philosophy of piping data from one 
program to another. I'm sure I don't need to justify the benefits of Unix-
style tools, but if you don't like it, just combine the following two 
iterators into the lastModDate function that follows:


import os

def file_iter(dir='.', recurse=False):
for root, dirs, files in os.walk(dir):
if not recurse:
del dirs[:]
for file in files:
yield os.path.join(root, file)

def filetype_iter(extensions=None, dir='.', recurse=False):
if not extensions:
extensions = ['']
for file in file_iter(dir, recurse):
if os.path.splitext(file)[1] in extensions:
yield file

def lastModDate(dir=None, recurse=False):
"""Return the latest modification date of any Python source file."""
if dir is None:
dir = os.path.dirname(__file__)
if dir == '':
dir = '.'  # HACK, but appears necessary
return max( (os.path.getmtime(name) for name 
in filetype_iter(['.py'], dir, recurse)) )


It will raise a ValueError if there are no .py files in the directory, 
but that's easily changed.

Note also that I've changed lastModDate() to return the raw date stamp 
rather than a human readable string. The right place to covert to a human 
readable format is just before displaying it to a human being :)




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


Re: reading file to list

2009-01-20 Thread Xah Lee
On Jan 19, 11:17 pm, alex23  wrote:
...

Hi Daniel Weinreb,

Xah wrote:
> • A Ruby Illustration of Lisp Problems
>  http://xahlee.org/UnixResource_dir/writ/lisp_problems_by_ruby.html
Daniel Weinreb wrote:
> Xah Lee: Elisp is an interesting choice.  But without converting the
> strings to integers, it's not really right.

i did post a correction quickly that includes the conversion to
string/
num. Here's the full code:

(defun read-lines (file)
  "Return a list of lines in FILE."
  (with-temp-buffer
(insert-file-contents file)
(split-string
 (buffer-string) "\n" t)
)
  )

(mapcar
 (lambda (x)
   (mapcar
(lambda (y) (string-to-number y) )
(split-string x " ")
)
   )
 (read-lines "blob.txt")
 )

> It's interesting that Elisp already has a style of reading in the
> whole file, but no built-in to convert strings to integers, whereas
> Common Lisp is the other way around.

> The statement "It is not so mostly because emacs people have drawn
> themselves into a elitist corner, closing off to the outside world" is
> just a rude ad hominem attack.

sure. In a political context, many criticism or description of the
situation from one party can be seen as ad hominem attack. I feel that
that many old emacs users, which includes significant portion of emacs
developers (if not majority), are so exteremly bottled up and turn
down any possibility of advancing. They are killing emacs. (similar
feelings for most regular posters here in comp.lang.lisp )

Now, that statement is imprecise, is attacking, needs a lot
qualifications. I have literally written about 20 articles each a
thousand words or more over the past 3 years that explains many
specific cases in painful detail. (e.g. 
seehttp://xahlee.org/emacs/emacs_essays_index.html
) However, in a one sentence description in this thread's context,
calling them “elitist” and “closing off to the outside world”, is to
the point.

> Your claim that this shows something wrong with lists is completely
> unclear, although if I read your paper (I'll try) I might have some
> idea what you're getting at

More specifically, 2 fundamental problems of lisp i feel this ruby
example illustrates well:

• the cons impedes many aspects of lists. e.g. difficult to learn,
confusing, hard to use, prevent development of coherent list
manipulation functions.

• nested syntax impedes the functional programing paradigm of function
chaining, esp when each function has 2 or more arguments (e.g. map).

here's a short summary of the nesting problem:

(map f x) ; 1 level of chaining
(map g (map f x)) ; 2 levels
(map h (map g (map f x))) ; 3 levels

compare:

x | f | g | h   > unix pipe
x // f // g // h   > Mathematica
h @ g @ f @ x> Mathematica
x.f.g.h---> various OOP langs, esp Ruby, javascript
h g f x   ---> some functional langs, Haskell, Ocaml

The way the above works is that each of f, g, h is a lambda themselves
that maps. (that is, something like “(lambda (y) (map f y))”)

Note, that any of the f, g, h may be complex pure functions (aka
lambda).  Because in lisp, each lambda itself will in general have
quite a lot nested parens (which cannot be avoided), so this makes any
chaining of functions of 2 args, for more than 2 or 3 levels of
nesting, unusable for practical coding. One must define the functions
separately and just call their names, or use function composition with
lambda (which gets complex quickly). One major aspect of this problem
is that the scope of vars becomes hard to understand in the deep
nested source code. This is worse in elisp, because emacs is
dynamically scoped, so you have to avoid using var of same name.

More detail here:

the section “The Cons Business” at
• Fundamental Problems of Lisp
 http://xahlee.org/UnixResource_dir/writ/lisp_problems.html

• The Concepts and Confusions of Prefix, Infix, Postfix and Fully
Nested Notations
 http://xahlee.org/UnixResource_dir/writ/notations.html

Your input will be highly valued. Though, forgive me to say, that i
think my opinion on this is beyond any computer scientist of any
standing can try to tell me otherwise. If they disagree (which i think
most of them won't), i think their knowledge and experience in the
area of computer languages and syntax and notations, IQ, are inferior
to me.

 Xah
∑http://xahlee.org/

☄

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-20 Thread Duncan Booth
Luis Zarrabeitia  wrote:

> It boggles me when I see python code with properties that only set and
> get the attribute, or even worse, getters and setters for that
> purpose. In my university they teach the students to write properties
> for the attributes in C# ("never make a public attribute, always write
> a public property that just gets and sets it"). I never understood
> that practice either, given that the syntax for attribute access and
> property access in C# is exactly the same. (Could it be that even if
> the syntax is the same, the compiled code differs? Don't know enough
> about .NET to answer that). 
> 
The compiled code differs. That doesn't matter if the class is only 
accessed from within a single compiled program, but it does matter if you 
expose a public interface from a library: if you change a public attribute 
into a property then you need to recompile all code which accesses it.

Actually that's no worse than making any other change to the published 
interface, and the source code doesn't need to change, you just need to 
recompile.

Personally when writing C# I use properties when it seems like a good idea, 
but for small internal classes I just expose the attributes until I know I 
need to do something different.


-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-20 Thread Paul Rubin
Luis Zarrabeitia  writes:
> No wonder you can't get Bruno's point. For the second, static checks
> to prevent accidents, you have pylint. For the first, not only you
> are using the wrong tool, but you are barking at python for not
> having it. Assuming that pylint is perfect (big assumption, but it
> is up to you to prove where it fails), 

Whaat?  Assuming a program is perfect unless a failure is proven
is not at all a sane approach to getting reliable software.  It is
the person claiming perfection who has to prove the absence of failure.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Logging help

2009-01-20 Thread koranthala
On Jan 20, 5:45 am, Chris Rebert  wrote:
> On Mon, Jan 19, 2009 at 11:36 AM, koranthala  wrote:
> > Hi,
> >   Is it possible somehow to have the logging module rotate the files
> > every time I start it.
> >   Basically, I can automatically rotate using RotatingFileHandler;
> > Now I want it rotated every time I start the program too.
>
> Just call the .doRollover() method of the RotatingFileHandler at the
> start of the program.
> Reading The Fine Documentation for the module is helpful.
>
> Cheers,
> Chris
>
> --
> Follow the path of the Iguana...http://rebertia.com

My question was poorly framed. I will try to explain the issue a
little more.
Current doRollover method is not very helpful to rolling over every
day if the process starts and stops many times.
For example:
TimedRotatingFileHandler - when='D' Interval=1. I call
handler.doRollover everytime process starts.

First run - the output files are
log.txt
--
Second run - files are
log.txt, log.txt.2009-01-20
--
Till now, fine.
Third run - files are
log.txt, log.txt.2009-01-20 ***But the earlier file is overwritten***

The doRollover method does not append to the earlier file. Rather, it
creates a new file with the same name.
Due to this the earlier logs are all gone.

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


Re: Python 3: exec arg 1

2009-01-20 Thread Alan G Isaac

On 1/18/2009 9:36 AM Alan G Isaac apparently wrote:

I do not much care about the disappearance of ``execfile``.
I was asking, why is it a **good thing** that
``exec`` does not accept a TextIOWrapper?
Or is it just not implemented yet?
What is the gain from this particular backwards
incompatibility (in the sense that ``exec(open(fname))``
no longer works)?


Still interested in an answer...
Alan Isaac
--
http://mail.python.org/mailman/listinfo/python-list


Doubts related to subprocess.Popen()

2009-01-20 Thread srinivasan srinivas
Hi,
Does subprocess.Popen() count a new open file for each suprocess? I mean does 
it occupy an entry in file descriptor table of parent process?
If so, wat is each file descriptor connected to?

Thanks,
Srini


  Add more friends to your messenger and enjoy! Go to 
http://messenger.yahoo.com/invite/
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's the point of rpython?

2009-01-20 Thread skip

Carl> I just looked at the boost documentation, which claims that
Carl> multiple asynchronous writes to the same shared_ptr results in
Carl> undefined behavior.  That will not suffice for Python reference
Carl> counting.

Carl, I'm quite unfamiliar with Boost and am not a C++ person, so may have
read what you saw but not recognized it in the C++ punctuation soup.  I
couldn't find what you referred to.  Can you provide a URL?

Thanks,

-- 
Skip Montanaro - s...@pobox.com - http://smontanaro.dyndns.org/
--
http://mail.python.org/mailman/listinfo/python-list


How to start a transaction?

2009-01-20 Thread Hussein B
Hey,
I know the basics of interacting with databases in Python.
How to start a transaction in case I want to group a couple of insert
and update statements into a single operation?
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to start a transaction?

2009-01-20 Thread Diez B. Roggisch
Hussein B wrote:

> Hey,
> I know the basics of interacting with databases in Python.
> How to start a transaction in case I want to group a couple of insert
> and update statements into a single operation?

Please read the python database API documentation:

http://www.python.org/dev/peps/pep-0249/

And make sure your database supports transactions.

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


Re: what's the point of rpython?

2009-01-20 Thread Paul Rubin
s...@pobox.com writes:
> Carl, I'm quite unfamiliar with Boost and am not a C++ person, so may have
> read what you saw but not recognized it in the C++ punctuation soup.  I
> couldn't find what you referred to.  Can you provide a URL?

http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety

Note there is also something called "interprocess shared pointers"
(link below) that don't have that caveat.  I wonder if they use locks.

http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess/interprocess_smart_ptr.html#interprocess.interprocess_smart_ptr.shared_ptr
--
http://mail.python.org/mailman/listinfo/python-list


How to print lambda result ?

2009-01-20 Thread Barak, Ron
Hi,

Wanting to print the correct plural after numbers, I did the following:

for num in range(1,4):
string_ = "%d event%s" % (num,lambda num: num > 1 and "s" or "")
print string_

However, instead of getting the expected output:

1 event
2 events
3 events

I get:

1 event at 0x00AFE670>
2 event at 0x00AFE670>
3 event at 0x00AFE6B0>

Reading the first results of http://www.google.com/search?q=python+lambda 
didn't enlighten me.

Could you point to a URL which could set me on the right path to get the 
expected output ?

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


python resource management

2009-01-20 Thread S.Selvam Siva
Hi all,

I have found the actual solution for this problem.
I tried using BeautifulSoup.SoupStrainer() and it improved memory usage
to the greatest extent.Now it uses max of 20 MB(earlier
it was >800 MB on 1GB RAM system).
thanks all.

-- 
Yours,
S.Selvam
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to print lambda result ?

2009-01-20 Thread Tino Wildenhain

Hi,

Barak, Ron wrote:

Hi,

Wanting to print the correct plural after numbers, I did the following:

for num in range(1,4):
string_ = "%d event%s" % (num,lambda num: num > 1 and "s" or "")
print string_

However, instead of getting the expected output:

1 event
2 events
3 events

I get:

1 event at 0x00AFE670>
2 event at 0x00AFE670>
3 event at 0x00AFE6B0>


lambda creates a function so this is the result you
are seeing. You would need to call the function
to get your result.

(num,(lambda n: n >1 and "s" or "")(num))

which is just a quite useless application
of lambda :-)

(num,num >1 and "s" or "")

or even

(num,"s" if num >1 else "")

in python > 2.5

or in python <3.0:

(num,"s"*(num >1))

:-)

HTH
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


RE: How to print lambda result ?

2009-01-20 Thread Barak, Ron
Thanks Tino: your solutions without the lambda work nicely.
What I still don't understand is why the print does not execute the lambda and 
prints the result, instead of printing the lambda's object description.
Bye,
Ron.


-Original Message-
From: Tino Wildenhain [mailto:t...@wildenhain.de]
Sent: Tuesday, January 20, 2009 14:22
To: Barak, Ron
Cc: python-list@python.org
Subject: Re: How to print lambda result ?

Hi,

Barak, Ron wrote:
> Hi,
>
> Wanting to print the correct plural after numbers, I did the following:
>
> for num in range(1,4):
> string_ = "%d event%s" % (num,lambda num: num > 1 and "s" or "")
> print string_
>
> However, instead of getting the expected output:
>
> 1 event
> 2 events
> 3 events
>
> I get:
>
> 1 event at 0x00AFE670>
> 2 event at 0x00AFE670>
> 3 event at 0x00AFE6B0>

lambda creates a function so this is the result you are seeing. You would need 
to call the function to get your result.

(num,(lambda n: n >1 and "s" or "")(num))

which is just a quite useless application of lambda :-)

(num,num >1 and "s" or "")

or even

(num,"s" if num >1 else "")

in python > 2.5

or in python <3.0:

(num,"s"*(num >1))

:-)

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


Re: Doubts related to subprocess.Popen()

2009-01-20 Thread Diez B. Roggisch
srinivasan srinivas wrote:

> Hi,
> Does subprocess.Popen() count a new open file for each suprocess? I mean
> does it occupy an entry in file descriptor table of parent process? If so,
> wat is each file descriptor connected to?

Usually, each new process has three file-descriptors associated with it -
stdin,stdout and stderr.

So when you span a process, the overall count of FDs should increase by
three.

Additionally, there are more FDs created if you chose to pipe communication
between the child-process and the parent.

This is a unix-thing btw, nothing to do with subprocess per se.

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


Re: How to print lambda result ?

2009-01-20 Thread Tino Wildenhain

Barak, Ron wrote:

Thanks Tino: your solutions without the lambda work nicely.
What I still don't understand is why the print does not execute the lambda and 
prints the result, instead of printing the lambda's object description.
Bye,
Ron.


Well its up to the implemention what a class is supposed to return when 
its __str__() is called. Default is what you see. (this is actually

__str__() returning __repr__() which is at its default)

Regards
Tino



-Original Message-
From: Tino Wildenhain [mailto:t...@wildenhain.de]
Sent: Tuesday, January 20, 2009 14:22
To: Barak, Ron
Cc: python-list@python.org
Subject: Re: How to print lambda result ?

Hi,

Barak, Ron wrote:

Hi,

Wanting to print the correct plural after numbers, I did the following:

for num in range(1,4):
string_ = "%d event%s" % (num,lambda num: num > 1 and "s" or "")
print string_

However, instead of getting the expected output:

1 event
2 events
3 events

I get:

1 event at 0x00AFE670>
2 event at 0x00AFE670>
3 event at 0x00AFE6B0>


lambda creates a function so this is the result you are seeing. You would need 
to call the function to get your result.

(num,(lambda n: n >1 and "s" or "")(num))

which is just a quite useless application of lambda :-)

(num,num >1 and "s" or "")

or even

(num,"s" if num >1 else "")

in python > 2.5

or in python <3.0:

(num,"s"*(num >1))

:-)

HTH
Tino




smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


RE: How to print lambda result ?

2009-01-20 Thread Barak, Ron
Ah, okay.
Now it's clear.
Thanks Tino.
Ron.

-Original Message-
From: Tino Wildenhain [mailto:t...@wildenhain.de]
Sent: Tuesday, January 20, 2009 14:45
To: Barak, Ron
Cc: python-list@python.org
Subject: Re: How to print lambda result ?

Barak, Ron wrote:
> Thanks Tino: your solutions without the lambda work nicely.
> What I still don't understand is why the print does not execute the lambda 
> and prints the result, instead of printing the lambda's object description.
> Bye,
> Ron.

Well its up to the implemention what a class is supposed to return when its 
__str__() is called. Default is what you see. (this is actually
__str__() returning __repr__() which is at its default)

Regards
Tino

>
> -Original Message-
> From: Tino Wildenhain [mailto:t...@wildenhain.de]
> Sent: Tuesday, January 20, 2009 14:22
> To: Barak, Ron
> Cc: python-list@python.org
> Subject: Re: How to print lambda result ?
>
> Hi,
>
> Barak, Ron wrote:
>> Hi,
>>
>> Wanting to print the correct plural after numbers, I did the following:
>>
>> for num in range(1,4):
>> string_ = "%d event%s" % (num,lambda num: num > 1 and "s" or "")
>> print string_
>>
>> However, instead of getting the expected output:
>>
>> 1 event
>> 2 events
>> 3 events
>>
>> I get:
>>
>> 1 event at 0x00AFE670>
>> 2 event at 0x00AFE670>
>> 3 event at 0x00AFE6B0>
>
> lambda creates a function so this is the result you are seeing. You would 
> need to call the function to get your result.
>
> (num,(lambda n: n >1 and "s" or "")(num))
>
> which is just a quite useless application of lambda :-)
>
> (num,num >1 and "s" or "")
>
> or even
>
> (num,"s" if num >1 else "")
>
> in python > 2.5
>
> or in python <3.0:
>
> (num,"s"*(num >1))
>
> :-)
>
> HTH
> Tino

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


Re: ifconfig in python

2009-01-20 Thread Mark Wooding
Дамјан Георгиевски  writes:

> Something *like*  this could work:
>
>   myip = urllib2.urlopen('http://whatismyip.org/').read()

This is going to cause all manner of problems.

Firstly, many users are stuck behind NAT routers.  In this case, the
external service will report the address of the router, which is
probably useless -- certainly it will be for programs attempting to
communicate over a LAN.

Secondly, imagine the joy when overzealous ISPs decide that
whatismyip.org is peddling kiddiepr0n (as happened to Wikipedia last
month): then the service will report the address of ISP's censoring
proxy to thousands of otherwise unrelated users.

And that's before we get onto onion routers like Tor...

Here's an idea which might do pretty well.

In [1]: import socket as S
In [2]: s = S.socket(S.AF_INET, S.SOCK_DGRAM)
In [4]: s.connect(('192.0.2.1', 666))
In [5]: s.getsockname()
Out[5]: ('172.29.198.11', 46300)

(No packets were sent during this process: UDP `connections' don't need
explicit establishment.  The network 192.0.2.0/24 is reserved for use in
examples; selecting a local address should therefore exercise the
default route almost everywhere.  If there's a specific peer address or
network you want to communicate with, use that address explicitly.)

I have to wonder what the purpose of this is.  It's much better to have
the recipient of a packet work out the sender's address from the packet
(using recvfrom or similar) because that actually copes with NAT and so
on properly.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: ifconfig in python

2009-01-20 Thread rasikasriniva...@gmail.com
On Jan 20, 7:33 am, Mark Wooding  wrote:
> Дамјан Георгиевски  writes:
> > Something *like*  this could work:
>
> >    myip = urllib2.urlopen('http://whatismyip.org/').read()
>
> This is going to cause all manner of problems.
>
> Firstly, many users are stuck behind NAT routers.  In this case, the
> external service will report the address of the router, which is
> probably useless -- certainly it will be for programs attempting to
> communicate over a LAN.
>
> Secondly, imagine the joy when overzealous ISPs decide that
> whatismyip.org is peddling kiddiepr0n (as happened to Wikipedia last
> month): then the service will report the address of ISP's censoring
> proxy to thousands of otherwise unrelated users.
>
> And that's before we get onto onion routers like Tor...
>
> Here's an idea which might do pretty well.
>
> In [1]: import socket as S
> In [2]: s = S.socket(S.AF_INET, S.SOCK_DGRAM)
> In [4]: s.connect(('192.0.2.1', 666))
> In [5]: s.getsockname()
> Out[5]: ('172.29.198.11', 46300)
>
> (No packets were sent during this process: UDP `connections' don't need
> explicit establishment.  The network 192.0.2.0/24 is reserved for use in
> examples; selecting a local address should therefore exercise the
> default route almost everywhere.  If there's a specific peer address or
> network you want to communicate with, use that address explicitly.)
>
> I have to wonder what the purpose of this is.  It's much better to have
> the recipient of a packet work out the sender's address from the packet
> (using recvfrom or similar) because that actually copes with NAT and so
> on properly.
>
> -- [mdw]

one way to get your head around this is - IP Addresses are associated
with the interface and not the computer. distinction may be subtle but
critical.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to print lambda result ?

2009-01-20 Thread alex23
On Jan 20, 10:34 pm, "Barak, Ron"  wrote:
> What I still don't understand is why the print does not
> execute the lambda and prints the result, instead of
> printing the lambda's object description.

The following two statements are identical:

>>> def f(x): return x
...
>>> f = lambda x: x

lambda _creates_ a function, it's up to you to actually _call_ the
function. Functions are first class objects in Python, so the tuple
you're passing in to the string format contains a number and a
function.

Tino's solutions are definitely more what you're looking for, but for
your lambda version to work, you have to actually call the lambda
function, passing in num when you do so (as you've specified that the
lambda function requires one argument):

>>> for num in range(1, 4):
... string_ = "%d event%s" % (num, (lambda num: num > 1 and "s" or
"")(num))
... print string_

Or you can remove the argument and create a closure using the num
value from the loop:

... string_ = "%d event%s" % (num, (lambda: num > 1 and "s" or "")
())

But again, this is generally overkill when all you're after is a
conditional value.

Personally, I tend to use lambdas for passing small units of
functionality into other functions, or if I want to create a quick
closure. Your mileage may vary on what you consider a suitable use
case, but you will -still- have to call your lambda in order for it to
execute :)
Generally
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to print lambda result ?

2009-01-20 Thread Tim Northover
alex23  writes:

> On Jan 20, 10:34 pm, "Barak, Ron"  wrote:

 for num in range(1, 4):
> ... string_ = "%d event%s" % (num, (lambda num: num > 1 and "s" or
> "")(num))
> ... print string_

The notation here suggests Ron is sligtly confused about what he
created. It was equivalent to

string_ = "%d event%s" % (num, lambda x: x > 1 and "s" or "")

Notice that there's no actual mention of num there, it's a function that
takes one parameter. If that parameter happens to be num it does what
you want, but there's no way for the interpreter to know what was
intended.

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


Re: Doubts related to subprocess.Popen()

2009-01-20 Thread Mark Wooding
srinivasan srinivas  writes:

> Does subprocess.Popen() count a new open file for each suprocess? I
> mean does it occupy an entry in file descriptor table of parent
> process?  If so, wat is each file descriptor connected to?

On Unix, subprocess.Popen will use up a file descriptor in the parent
for each use of subprocess.PIPE.  The descriptor in question is one end
of a pipe; the child process holds the other end.

I guess the situation is similar on Windows, but I don't know for sure.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Why I'm getting the date of yesterday

2009-01-20 Thread Hussein B
Hey,
I'm trying to get the get the date before today, I tried this:
d = datetime.now() - timedelta(days = -1)
But I got the date of tomorrow.
when I tried:
d = datetime.now() + timedelta(days = -1)
I got the date of yesterday.
Would you please explain to me why I got the date of yesterday when I
added the both objects?
Thanks.

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


Re: Why I'm getting the date of yesterday

2009-01-20 Thread Simon Brunning
2009/1/20 Hussein B :
> Hey,
> I'm trying to get the get the date before today, I tried this:
> d = datetime.now() - timedelta(days = -1)
> But I got the date of tomorrow.

That's because you are taking away a negative value. This is like doing:

>>> 0 - (-1)
1

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-20 Thread Luis Zarrabeitia

On Tuesday 20 January 2009 02:00:43 am Russ P. wrote:
> On Jan 19, 10:33 pm, Luis Zarrabeitia  wrote:
> > (Why do you keep calling it 'encapsulation'?).
>
> I keep calling it encapsulation because that is a widely accepted,
> albeit not universal, definition of encapsulation. 

[...]

> Encapsulation conceals the functional details of a class from objects
> that send messages to it.

[..]

> Definition: In Object Oriented Programming, encapsulation is an
> attribute of object design. It means that all of the object's data is
> contained and hidden in the object and access to it restricted to
> members of that class.

Ahh, 'concealed', 'contained', 'hidden'. Except the last one, "hidden", python 
does the rest... and one could argue the self.__privs get pretty well hidden.

Not 'forbidden', 'restricted', 'enforced'.

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to start a transaction?

2009-01-20 Thread M.-A. Lemburg
On 2009-01-20 12:23, Hussein B wrote:
> Hey,
> I know the basics of interacting with databases in Python.
> How to start a transaction in case I want to group a couple of insert
> and update statements into a single operation?

If you use a Python DB-API compatible database module, then
transactions are enabled per default after you connect to the
database. connection.commit() and .rollback() then complete a
transaction and implicitly start a new one.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jan 20 2009)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-20 Thread Luis Zarrabeitia
On Tuesday 20 January 2009 05:00:34 am Paul Rubin wrote:
> Luis Zarrabeitia  writes:
> > No wonder you can't get Bruno's point. For the second, static checks
> > to prevent accidents, you have pylint. For the first, not only you
> > are using the wrong tool, but you are barking at python for not
> > having it. Assuming that pylint is perfect (big assumption, but it
> > is up to you to prove where it fails),
>
> Whaat?  Assuming a program is perfect unless a failure is proven
> is not at all a sane approach to getting reliable software.  It is
> the person claiming perfection who has to prove the absence of failure.

No, no. I meant that if pylint works as its specification says it would.

Russ says (or seems to say, I don't know, I'm confused already) that it is not 
good enough, that what pylint says it does is not what he wants (otherwise, 
this subthread would have died a long time ago). So, assuming that pylint 
works as specified (its up to "you" to find out if it doesn't and file 
bugreports about it, just like you would do if you find out that the 
static-checker for your enforced-static-checks-language is buggy), what
would be the difference between only accepting/running "pylint-authorized 
code" and the enforced hiding you desire?

Sorry, I didn't realize that perfect was a too strong word for that. "I speaks 
english bad" :D

Cya!

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-20 Thread Bruno Desthuilliers

Paul Rubin a écrit :

Bruno Desthuilliers  writes:

Take some not-that-trivial projects like Zope/Plone. There are quite a
few lines of code involved, and quite a lot of programmers worked on it.


Zope is about 375 KLOC[1],


I was thinking about Zope2 + Plone, but anyway...


which I agree is not trivial, but by
today's standards, it's not all that large. 


How many LOCS would it require if it was written in ADA ?


Zope also has 275 open
bugs, 6 of which are critical.


None of which are going to *kill* anyone FWIW. Now how many of these 
bugs would have language-enforced access restriction prevented ?



[2] The Space Shuttle avionics (written
in the 1980's!) are 2 MLOC 


of a hi-level dynamic language ? Hm, I guess not.


in which only 3 errors have been found
post-release.[3] I think "large software system" today means 100's of
MLOC.


Given the difference in LOCS count between a low-level static language 
and a hi-level dynamic language for the implementation of a same given 
features set, you cannot just define "large" by the # of LOCS. Not that 
I'm going to compare Zope with Space shuttle's stuff.



 FWIW, Zope has 20x as much code as Django--is that a good
thing!?


IMHO, definitively not - and I indeed prefer Django as far as I'm 
concerned. But this is another debate (or is it not ?...)


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


Re: Embedding Python. But not so easy.

2009-01-20 Thread Diez B. Roggisch
> 1) Threads: the simulation is going to be run in a very parallel
> environment with several CPUs and
> http://docs.python.org/c-api/init.html#thread-state-and-
> the-global-interpreter-lock there is a global lock mentioned. Does that
> mean that the python code can not benefit from this ?

Not if it is CPU-bound, no. To overcome that, you'd either need multiple
processes, or you could try & trick the python interpreter by using renamed
DLLs, which means that  you can start several interpreters in one process.

*BUT* that's a nasty hack & you can't share objects between the
interpreters.


> 2) The script has to hand back control to the C++ framework without
> increasing the C execution stack. and be able to resume the execution at a
> later point.
> 
> I try some pseudo code here to explain
> 
> // C++:
> ctx = new ExecutionContext();
> 
> ctx->run();
> while(ctx->stillRunning()) {
> otherStuff();
> ctx->resume();
> }

Stackless python might be of help here, google it.

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


A SSH error during put operation

2009-01-20 Thread Oltmans
Hey all,

I've been using Paramiko for sometime now and I never had any
problems. I've already submitted this question to Paramiko mailling
list but I thought I should post it in CLP as someone might have used
it in past. I'm using Paramiko for SSH. Are there any other good SSH
libraries that you've found useful--please let me know?
There is this script that used to work absolutely fine. But for some
reason it's broken now. First, here is the script. Error is pasted at
the end. Please help as I've searched the Internet, archives but
couldn't find anything and it's been quite a few hours now. I will
really appreciate any help. Thanks in advance.

Script:
from __future__ import with_statement
import paramiko
import base64,os, sys
from paramiko import AutoAddPolicy, SSHClient
from decimal import *
class CustomException(Exception):
 def __init__(self, value):
  self.parameter = value
 def __str__(self):
  return repr(self.parameter)

def ConnectCopy(domainInfo, uname, pwd,
portNumber,zipName,completePath):

#domainInfo is a list, where domainInfo[0] = host name and
#domainInfo[1] is the remote path.
#
#zipName is the name of zip file. It will be appended with
domainInfo[1] so
#it will look like c:\Test\ABC.zip
#
#completePath is the local file path , that we intend to copy to
remote host

domainName=""
domainName=domainInfo[0].strip()
client= paramiko.SSHClient()

client.set_missing_host_key_policy(AutoAddPolicy())
print 'Complete Path= '+completePath

try:
client.connect
(domainName,portNumber,username=uname,password=pwd)
except CustomException, (e):
print "Error="+e.parameter


print "Domain Info= "+domainInfo[1]

try:
sftp=client.open_sftp()
sftp.put(os.path.normpath(completePath),os.path.normpath
(domainInfo[1])+"\\"+zipName)
sys.stdout.write('\n')
print 'File has been copied'
except CustomException,(e):
print "Error = "+e.parameter
sys.exit()




sftp.close()
client.close()




if __name__=="__main__":
ConnectCopy(['example.example.com','C:\\test'],'username','pwd',
8922,'ABC.zip','C:\\ABC.zip')





and here is the Error:

Microsoft Windows 2000 [Version 5.00.2195]
(C) Copyright 1985-2000 Microsoft Corp.



C:\Release>connectdeploy1.py


Traceback (most recent call last):
  File "C:\Release\ConnectDeploy1.py", line 56, in 
ConnectCopy(['example.example.com','C:\\test'],'username','pwd',
8922,'ABC.zip','C:\\ABC.zip')
  File "C:\Release\ConnectDeploy1.py", line 39, in ConnectCopy
sftp.put(os.path.normpath(completePath),os.path.normpath(domainInfo
[1]))
  File "C:\Python25\lib\site-packages\paramiko\sftp_client.py", line
539, in put

fr = self.file(remotepath, 'wb')
  File "C:\Python25\lib\site-packages\paramiko\sftp_client.py", line
238, in ope
n
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
  File "C:\Python25\lib\site-packages\paramiko\sftp_client.py", line
589, in _re
quest
return self._read_response(num)
  File "C:\Python25\lib\site-packages\paramiko\sftp_client.py", line
637, in _re
ad_response
self._convert_status(msg)
  File "C:\Python25\lib\site-packages\paramiko\sftp_client.py", line
667, in _co
nvert_status
raise IOError(text)
IOError: SfsStatusCode.Failure

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


Re: Doubts related to subprocess.Popen()

2009-01-20 Thread srinivasan srinivas
Do parent process will have different file descriptor in it for each 
subprocesses or paprent uses a single file descriptor for all?
I really want to know creation of each subprocess will occupy an entry in 
parents'file descriptor table. B'cos if i create more than 200 subprocesses, i 
am getting 'Too many open files' error.

Thanks,
Srini
- Original Message 
From: Mark Wooding 
To: python-list@python.org
Sent: Tuesday, 20 January, 2009 6:16:17 PM
Subject: Re: Doubts related to subprocess.Popen()

srinivasan srinivas  writes:

> Does subprocess.Popen() count a new open file for each suprocess? I
> mean does it occupy an entry in file descriptor table of parent
> process?  If so, wat is each file descriptor connected to?

On Unix, subprocess.Popen will use up a file descriptor in the parent
for each use of subprocess.PIPE.  The descriptor in question is one end
of a pipe; the child process holds the other end.

I guess the situation is similar on Windows, but I don't know for sure.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list



  Add more friends to your messenger and enjoy! Go to 
http://messenger.yahoo.com/invite/
--
http://mail.python.org/mailman/listinfo/python-list


How to get first/last day of the previous month?

2009-01-20 Thread Hussein B
Hey,
I'm creating a report that is supposed to harvest the data for the
previous month.
So I need a way to get the first day and the last day of the previous
month.
Would you please tell me how to do this?
Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to print lambda result ?

2009-01-20 Thread D'Arcy J.M. Cain
On Tue, 20 Jan 2009 12:34:04 +
"Barak, Ron"  wrote:
> Thanks Tino: your solutions without the lambda work nicely.
> What I still don't understand is why the print does not execute the lambda 
> and prints the result, instead of printing the lambda's object description.

Because that's what you told it.  Consider the even simpler example...

 "%s" % lambda num: int(num)

This is equivalent to...

 "%s" % int

IOW, you are giving the function (anonymous in your case), not the
result of calling it.  Your code prints a representation of exactly
what you gave it, an anonymous function that would return a string if
you called it with a number.

> > for num in range(1,4):
> > string_ = "%d event%s" % (num,lambda num: num > 1 and "s" or "")

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Doubts related to subprocess.Popen()

2009-01-20 Thread Philip Semanchuk


On Jan 20, 2009, at 9:19 AM, srinivasan srinivas wrote:

Do parent process will have different file descriptor in it for each  
subprocesses or paprent uses a single file descriptor for all?
I really want to know creation of each subprocess will occupy an  
entry in parents'file descriptor table. B'cos if i create more than  
200 subprocesses, i am getting 'Too many open files' error.


If you're on Unix, a command like lsof can be useful at a time like  
this.


lsof = "ls open files"

If you're on Linux, there's the /proc tree to investigate.







- Original Message 
From: Mark Wooding 
To: python-list@python.org
Sent: Tuesday, 20 January, 2009 6:16:17 PM
Subject: Re: Doubts related to subprocess.Popen()

srinivasan srinivas  writes:


Does subprocess.Popen() count a new open file for each suprocess? I
mean does it occupy an entry in file descriptor table of parent
process?  If so, wat is each file descriptor connected to?


On Unix, subprocess.Popen will use up a file descriptor in the parent
for each use of subprocess.PIPE.  The descriptor in question is one  
end

of a pipe; the child process holds the other end.

I guess the situation is similar on Windows, but I don't know for  
sure.


-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list



 Add more friends to your messenger and enjoy! Go to 
http://messenger.yahoo.com/invite/
--
http://mail.python.org/mailman/listinfo/python-list


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


SetUp functions for multiple test cases

2009-01-20 Thread Georg Schmid
I've just started working with unittests and already hit a snag. I
couldn't find out how to implement a setup function, that is executed
only _once_ before all of the tests. Specifically, I need this for
testing my database interface, and naturally I don't want to create a
new database in-memory and fill it with example data for every single
test case.
Obviously I could simply execute that setup function separately from
the unittesting procedure, but then there'd be no point in
implementing all my unittests in a clean manner in the first place,
apart from further problems arising due to how my IDE (Eric4) picks
test cases from project files.
Perhaps I missed something about the concept of TestSuites. Thanks in
advance!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to print lambda result ?

2009-01-20 Thread D'Arcy J.M. Cain
On Tue, 20 Jan 2009 09:26:14 -0500
"D'Arcy J.M. Cain"  wrote:
>  "%s" % lambda num: int(num)

Of course I meant...
  "%s" % (lambda num: int(num))

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get first/last day of the previous month?

2009-01-20 Thread Mike Driscoll
On Jan 20, 8:19 am, Hussein B  wrote:
> Hey,
> I'm creating a report that is supposed to harvest the data for the
> previous month.
> So I need a way to get the first day and the last day of the previous
> month.
> Would you please tell me how to do this?
> Thanks in advance.

I recommend the dateutil module:

http://labix.org/python-dateutil

I think it may also be possible to use the datetime module, but it's
easier to just use dateutil.

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


Re: How to get first/last day of the previous month?

2009-01-20 Thread Diez B. Roggisch
Hussein B wrote:

> Hey,
> I'm creating a report that is supposed to harvest the data for the
> previous month.
> So I need a way to get the first day and the last day of the previous
> month.
> Would you please tell me how to do this?

First day: create a new date-object with the day==1.

Last day: create a date-object with month + 1 and day==1, and subtract a
timedelta with one day of it.

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


Re: SetUp functions for multiple test cases

2009-01-20 Thread Diez B. Roggisch
Georg Schmid wrote:

> I've just started working with unittests and already hit a snag. I
> couldn't find out how to implement a setup function, that is executed
> only _once_ before all of the tests. Specifically, I need this for
> testing my database interface, and naturally I don't want to create a
> new database in-memory and fill it with example data for every single
> test case.
> Obviously I could simply execute that setup function separately from
> the unittesting procedure, but then there'd be no point in
> implementing all my unittests in a clean manner in the first place,
> apart from further problems arising due to how my IDE (Eric4) picks
> test cases from project files.
> Perhaps I missed something about the concept of TestSuites. Thanks in
> advance!

Why don't you simply store the state of the DB being set-up somewhere
(globally for example), and only execute the db-setup-code (inside setUp of
course) depending on the value of that variable?

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


Re: SetUp functions for multiple test cases

2009-01-20 Thread Roy Smith
In article 
<45b0bf56-673c-40cd-a27a-62f9943d9...@r41g2000prr.googlegroups.com>,
 Georg Schmid  wrote:

> I've just started working with unittests and already hit a snag. I
> couldn't find out how to implement a setup function, that is executed
> only _once_ before all of the tests. Specifically, I need this for
> testing my database interface, and naturally I don't want to create a
> new database in-memory and fill it with example data for every single
> test case.

Short answer -- there's no way to do it in the unittest framework.

The True Unit Test Zealots will argue that all tests should be 100% 
independent of each other, which means there should be NO common state 
between test cases.  For that matter, they will also argue that unit tests 
should not interface with external resources like databases.  And they're 
right.

On the other hand, the Real World Test Pragmatists will argue that this is 
just not practical in all cases.  Real programs have classes which interact 
with the outside world, and they need to get tested.  You could stub out 
the external resource, but that's a lot of work, and may introduce as many 
problems as it solves.  Sometimes, a big part of what you're testing is 
your understanding of the external world (i.e. "does this really work like 
it's documented?").

Plus, some operations are just too expensive to do for every test case.  I 
don't know how long it takes to build your in-memory database.  If it takes 
one second, it probably makes sense to do it for every test case (unless 
you've got thousands of test cases).  If it takes 10 minutes, then it makes 
sense to do it once and deal with the fact that you're violating True Unit 
Test Dogma.

Anyway, do what I do.  I run the tests with a:

if __name__ == "__main__":
   blah blah

block at the bottom of the test file.  Just do your "do once" setup in that 
code block and store the result in a global.

You might have your setUp() method re-assign the global to an instance 
variable and then your test cases can access it via self.whatever.  The 
reason for that is if at some point in the future you change your mind and 
decide to re-build the database in setUp() for each test, you just have to 
change setUp(), not touch the individual test cases.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Logging help

2009-01-20 Thread Gabriel Genellina
En Tue, 20 Jan 2009 08:11:52 -0200, koranthala   
escribió:

On Jan 20, 5:45 am, Chris Rebert  wrote:
On Mon, Jan 19, 2009 at 11:36 AM, koranthala   
wrote:



>   Is it possible somehow to have the logging module rotate the files
> every time I start it.
>   Basically, I can automatically rotate using RotatingFileHandler;
>   ^^^ >  
Now I want it rotated every time I start the program too.


Just call the .doRollover() method of the RotatingFileHandler at the
  ^^^ start of  
the program.

Reading The Fine Documentation for the module is helpful.


Current doRollover method is not very helpful to rolling over every
day if the process starts and stops many times.
For example:
TimedRotatingFileHandler - when='D' Interval=1. I call
 handler.doRollover everytime process starts.


Why the move to TimedRotatingFileHandler?

--
Gabriel Genellina

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


Re: Logging help

2009-01-20 Thread Gabriel Genellina
En Tue, 20 Jan 2009 08:11:52 -0200, koranthala   
escribió:

On Jan 20, 5:45 am, Chris Rebert  wrote:
On Mon, Jan 19, 2009 at 11:36 AM, koranthala   
wrote:



>   Is it possible somehow to have the logging module rotate the files
> every time I start it.
>   Basically, I can automatically rotate using RotatingFileHandler;
>   ^^^ >  
Now I want it rotated every time I start the program too.


Just call the .doRollover() method of the RotatingFileHandler at the
  ^^^ start of  
the program.

Reading The Fine Documentation for the module is helpful.


Current doRollover method is not very helpful to rolling over every
day if the process starts and stops many times.
For example:
TimedRotatingFileHandler - when='D' Interval=1. I call
 handler.doRollover everytime process starts.


Why the move to TimedRotatingFileHandler?

--
Gabriel Genellina

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


Re: How to get first/last day of the previous month?

2009-01-20 Thread Carsten Haese
Hussein B wrote:
> Hey,
> I'm creating a report that is supposed to harvest the data for the
> previous month.
> So I need a way to get the first day and the last day of the previous
> month.

In order to not deprive you of the sense of accomplishment from figuring
things out for yourself, I'll give you a couple of hints instead of
fully formed Python code:

1) Think about how you can find the first day of the *current* month.

2) Think about how you can get to the last day of the previous month
from there.

3) Think about how you can get to the first day of the previous month
from there.

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get first/last day of the previous month?

2009-01-20 Thread Marco Mariani

Hussein B wrote:


I'm creating a report that is supposed to harvest the data for the
previous month.
So I need a way to get the first day and the last day of the previous
month.
Would you please tell me how to do this?
Thanks in advance.


dateutil can do this and much, much more.


>>> from datetime import date
>>> from dateutil.relativedelta import relativedelta
>>> today = date.today()
>>> d = today - relativedelta(months=1)
>>> date(d.year, d.month, 1)
datetime.date(2008, 12, 1)
>>> date(today.year, today.month, 1) - relativedelta(days=1)
datetime.date(2008, 12, 31)
>>>

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


Re: How to print lambda result ?

2009-01-20 Thread alex23
On Jan 20, 10:57 pm, Tim Northover  wrote:
> Notice that there's no actual mention of num there, it's a function that
> takes one parameter. If that parameter happens to be num it does what
> you want, but there's no way for the interpreter to know what was
> intended.

Which is why my working example explicitly passed num into the lambda,
and why my variant used a closure...

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


Re: How to get first/last day of the previous month?

2009-01-20 Thread Marco Mariani

Carsten Haese wrote:


In order to not deprive you of the sense of accomplishment


Sorry for spoiling that. If you still want the sense of accomplishment, 
try to reimplement dateutil (and rrule). It's not as easy as it seems :-o


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


smtplib.SMTP throw : 'Socket error: 10053 software caused connection abort'

2009-01-20 Thread aberry

I am using 'smtplib' module to send an email but getting exception...

smtplib.SMTP( throw error :

here is trace back snippet :-

"   smtp = smtplib.SMTP(self.server)
 File "D:\Python24\lib\smtplib.py", line 244, in __init__
   (code, msg) = self.connect(host, port)
 File "D:\Python24\lib\smtplib.py", line 306, in connect
   raise socket.error, msg
socket.error: (10053, 'Software caused connection abort')"

thanks in adv,
aberry



-- 
View this message in context: 
http://www.nabble.com/smtplib.SMTP-throw-%3A-%27Socket-error%3A-10053-software-caused-connection-abort%27-tp21565011p21565011.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: How to get first/last day of the previous month?

2009-01-20 Thread Carsten Haese
Marco Mariani wrote:
> dateutil can do this and much, much more.

Using dateutil for this is like using a sledgehammer to kill a fly. The
task at hand can (and IMHO should) be solved with the standard datetime
module.

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get first/last day of the previous month?

2009-01-20 Thread Tim Chase

I'm creating a report that is supposed to harvest the data for the
previous month.
So I need a way to get the first day and the last day of the previous
month.
Would you please tell me how to do this?


>>> from datetime import date, datetime, timedelta
>>> def prev_bounds(when=None):
... if not when: when = datetime.today()
... this_first = date(when.year, when.month, 1)
... prev_end = this_first - timedelta(days=1)
... prev_first = date(prev_end.year, prev_end.month, 1)
... return prev_first, prev_end
...
>>> prev_bounds()
(datetime.date(2008, 12, 1), datetime.date(2008, 12, 31))
>>> prev_bounds(datetime.date(2008,3,14)
(datetime.date(2008, 2, 1), datetime.date(2008, 2, 29))

-tkc




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


Re: How to get first/last day of the previous month?

2009-01-20 Thread Marco Mariani

Carsten Haese wrote:


dateutil can do this and much, much more.


Using dateutil for this is like using a sledgehammer to kill a fly. The
task at hand can (and IMHO should) be solved with the standard datetime
module.


Sure, but many python programmers are not even aware of the existence of 
that particular sledgehammer, it deserved to be mentioned. It should be 
part of the standard library I think.


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


Re: Two questions about style and some simple math

2009-01-20 Thread J Kenneth King
Spoofy  writes:

> ..  ..
>
> 2.
>
> For maintaining the character attributes I creates a seperate class. I
> wonder weather this is an "overuse" of OO (instead of just making the
> attributes plain variables of the Char class) and if the way I wrote
> this is OK (somehow this looks cool to me but maybe too "showy"?)
>
> class Attributes(object):
> ATTRIBUTES = {"attack": 0, "defence": 0, "ability": 0, "courage":
> 0, "condition": 0}
> def __init__(self, **kwargs):
> self.__dict__.update(self.ATTRIBUTES)
> for arg in kwargs:
> if arg not in self.ATTRIBUTES:
> raise ValueError("Unkown character attribute '%s'" %
> arg)
> self.__dict__[arg] = kwargs[arg]
>
>
> Again, I appreciate any tips. I you need more code (for the bigger
> picture or such), just ask.
>
> Thanks in advance

I think the first part has been covered well.

If you want an opinion, this class isn't "showy" at all, rather it is
ugly and unnecessary.

Firstly it's bad because:

1. ATTRIBUTES is still modifiable after insantiation. This breaks the
restriction you're expressing in __init__

2. You want to avoid modifying __dict__ directly if you can. It bypasses
the whole point of using named attributes.

What you'd really want in a case where a class has a restricted set of
attributes is __slots__. Classes defined with it have no __dict__ and
thus attributes cannot be dynamically added to them after
instanciation (a __slots__ defined class will raise an exception in this
case).

However, even in this case, it doesn't make sense to encapsulate the
attributes of your game's Character objects in this way. Your "Hero"
class should have its attributes directly associated to it: Hero.health,
Hero.defence, and so forth. If you want to encapsulate a common set of
attributes available to a "class" of objects, you'd create a "Character"
class with those general attributes, sub-class your NPC's and Hero from
it, and specialize those sub-classes as needed.

HTH,

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


Re: SetUp functions for multiple test cases

2009-01-20 Thread Georg Schmid
On Jan 20, 3:57 pm, Roy Smith  wrote:
> In article
> <45b0bf56-673c-40cd-a27a-62f9943d9...@r41g2000prr.googlegroups.com>,
>  Georg Schmid  wrote:
>
> > I've just started working with unittests and already hit a snag. I
> > couldn't find out how to implement a setup function, that is executed
> > only _once_ before all of the tests. Specifically, I need this for
> > testing my database interface, and naturally I don't want to create a
> > new database in-memory and fill it with example data for every single
> > test case.
>
> Short answer -- there's no way to do it in the unittest framework.
>
> The True Unit Test Zealots will argue that all tests should be 100%
> independent of each other, which means there should be NO common state
> between test cases.  For that matter, they will also argue that unit tests
> should not interface with external resources like databases.  And they're
> right.
>
> On the other hand, the Real World Test Pragmatists will argue that this is
> just not practical in all cases.  Real programs have classes which interact
> with the outside world, and they need to get tested.  You could stub out
> the external resource, but that's a lot of work, and may introduce as many
> problems as it solves.  Sometimes, a big part of what you're testing is
> your understanding of the external world (i.e. "does this really work like
> it's documented?").
>
> Plus, some operations are just too expensive to do for every test case.  I
> don't know how long it takes to build your in-memory database.  If it takes
> one second, it probably makes sense to do it for every test case (unless
> you've got thousands of test cases).  If it takes 10 minutes, then it makes
> sense to do it once and deal with the fact that you're violating True Unit
> Test Dogma.
>
> Anyway, do what I do.  I run the tests with a:
>
> if __name__ == "__main__":
>    blah blah
>
> block at the bottom of the test file.  Just do your "do once" setup in that
> code block and store the result in a global.
>
> You might have your setUp() method re-assign the global to an instance
> variable and then your test cases can access it via self.whatever.  The
> reason for that is if at some point in the future you change your mind and
> decide to re-build the database in setUp() for each test, you just have to
> change setUp(), not touch the individual test cases.

Thanks, exactly what I needed to know.
--
http://mail.python.org/mailman/listinfo/python-list


RE: ifconfig in python

2009-01-20 Thread bruce
hi...

in general, i've found that using "route" to find the iface for the default
gets me the interface in use... i then parse either ifconfig/iwconfig, to
get the address of the nic for that interface.. it's worked ok so far on
most machines i've dealt with...

thoughts/comments are of course welcome!


-Original Message-
From: python-list-bounces+bedouglas=earthlink@python.org
[mailto:python-list-bounces+bedouglas=earthlink@python.org]on Behalf
Of Ned Deily
Sent: Monday, January 19, 2009 6:49 PM
To: python-list@python.org
Subject: Re: ifconfig in python


In article
,
 "James Mills"  wrote:

> On Tue, Jan 20, 2009 at 10:28 AM, Nehemiah Dacres 
> wrote:
> > Is ther an easy way to get the resolved ip address of the machine a
script
> > is running on? socket.gethostbyname(socket.gethostname) has only
returned
> > the ip address of my loop back interface ... not very usefull.
>
> That's because your /etc/hosts resolves
> your hostname to 127.0.0.1 :)
>
> And no I know of no "easy" way cross
> platform way. Perhaps parsing the output
> of ifconfig itself ?

Also, since the subject is on my brain at the moment, how to find "the
address" is not the right question to ask.  These days most systems have
multiple network interfaces (Ethernet, WiFi, dialup, et al) running
multiple protocols, like IPv4 and IPv6.  In general, there is no *one*
IP address of a machine; often there are many.  Ignoring that fact can
lead to subtle bugs, like the one causing a urllib2 regression test
failure that I've been squashing today!

--
 Ned Deily,
 n...@acm.org

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

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


Re: Problem with IDLE on windows XP

2009-01-20 Thread Gabriel Genellina
En Mon, 19 Jan 2009 20:50:43 -0200, Grimes, George   
escribió:


I am trying to learn Python and I installed version 2.6 both at home and  
at work.  At home, on
Vista, everything works fine.  At work, on XP, IDLE would not run.  I  
uninstalled/reinstalled
and got the same thing.  My cursor changes to the wait symbol for a few  
seconds, then goes
back to normal and ….nothing.  The Task Manager shows nothing.  I  
uninstalled again,
made sure all the files were deleted from the disk, used regedit to  
delte every registry entry

that had python in it and tried version 3.0.

Geuss, what?  I still can’t run IDLE on XP?  Is this a common problem?   
Or am I unique?


Did you install "for all users" (as Administrator) or "just for me"?

The following instructions assume you installed Python 2.6 on C:\Python26  
-- replace with your own directory if different.


Open a command prompt (go to Start, Run, type "cmd" and press Enter).
At the > prompt type:

c:\Python26\python -V

and press Enter. Should reply with the Python version. Then try with:

c:\Python26\python c:\Python26\Lib\idlelib\idle.pyw

Should start IDLE, probably you get some error message; post it here.

--
Gabriel Genellina

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


Re: How to get first/last day of the previous month?

2009-01-20 Thread Hussein B
On Jan 20, 5:04 pm, Carsten Haese  wrote:
> Hussein B wrote:
> > Hey,
> > I'm creating a report that is supposed to harvest the data for the
> > previous month.
> > So I need a way to get the first day and the last day of the previous
> > month.
>
> In order to not deprive you of the sense of accomplishment from figuring
> things out for yourself, I'll give you a couple of hints instead of
> fully formed Python code:
>
> 1) Think about how you can find the first day of the *current* month.
>
> 2) Think about how you can get to the last day of the previous month
> from there.
>
> 3) Think about how you can get to the first day of the previous month
> from there.
>
> Hope this helps,
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

Thanks all for the reply.
Yes, I prefer to use the standard library.
Talking about the third step:
You told me to think how to get the first day of the previous month,
well how to know if the previous month is 28, 29, 30 or 31 days?
I'm new to Python, so forgive my questions.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get first/last day of the previous month?

2009-01-20 Thread Tim Chase

You told me to think how to get the first day of the previous month,
well how to know if the previous month is 28, 29, 30 or 31 days?


Find the first day of the *current* month, and then subtract one 
day (use the timedelta object).  You'll end up with the last day 
of the previous month as a date/datetime object.


-tkc



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


Re: SetUp functions for multiple test cases

2009-01-20 Thread Duncan Booth
Roy Smith  wrote:

> You might have your setUp() method re-assign the global to an instance
> variable and then your test cases can access it via self.whatever. 
> The reason for that is if at some point in the future you change your
> mind and decide to re-build the database in setUp() for each test, you
> just have to change setUp(), not touch the individual test cases.

Or you could use a class attribute to save the database connection.

Set it up the first time the test runs but on subsequent tests just use the 
saved values. If you have tests spread across separate files you could even 
set up the database connection in a base class and so it only gets created 
once across any number of test suites.

This has the advantage that your test will work even if not invoked as the 
main script. Putting the setup code inside name=='__main__' will break as 
soon as you have multiple test files.

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


file write collision consideration

2009-01-20 Thread RGK
I have a thread that is off reading things some of which will get 
written into a file while another UI thread manages input from a user.


The reader-thread and the UI-thread will both want to write stuff to the 
same output file. What first comes to mind is that there may be write 
collisions, ie both trying to write at the same time.


Should I do something like:


if busyFlag:
  while busyFlag:
 sleep(10)
else:
  busyFlag = True
  {write stuff to file}
  busyFlag = False


in both threads?   Is there some other approach that would be more 
appropriate?


Thanks in advance for your advice
- Ross.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Doubts related to subprocess.Popen()

2009-01-20 Thread Jeff McNeil
On Jan 20, 9:19 am, srinivasan srinivas 
wrote:
> Do parent process will have different file descriptor in it for each 
> subprocesses or paprent uses a single file descriptor for all?
> I really want to know creation of each subprocess will occupy an entry in 
> parents'file descriptor table. B'cos if i create more than 200 subprocesses, 
> i am getting 'Too many open files' error.
>
> Thanks,
> Srini
>
> - Original Message 
> From: Mark Wooding 
> To: python-l...@python.org
> Sent: Tuesday, 20 January, 2009 6:16:17 PM
> Subject: Re: Doubts related to subprocess.Popen()
>
> srinivasan srinivas  writes:
>
> > Does subprocess.Popen() count a new open file for each suprocess? I
> > mean does it occupy an entry in file descriptor table of parent
> > process?  If so, wat is each file descriptor connected to?
>
> On Unix, subprocess.Popen will use up a file descriptor in the parent
> for each use of subprocess.PIPE.  The descriptor in question is one end
> of a pipe; the child process holds the other end.
>
> I guess the situation is similar on Windows, but I don't know for sure.
>
> -- [mdw]
> --http://mail.python.org/mailman/listinfo/python-list
>
>   Add more friends to your messenger and enjoy! Go 
> tohttp://messenger.yahoo.com/invite/

Have you upped your open files limit?  My test script:

import subprocess

procs = []
for i in xrange(400):
procs.append(subprocess.Popen("/bin/cat",
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE))

By default, 'ulimit -n' returns 1024, which is the number of open
files allowed.  Running the test script without changing it results
in:

Traceback (most recent call last):
  File "test.py", line 9, in 
stderr=subprocess.PIPE))
  File "/usr/lib/python2.5/subprocess.py", line 593, in __init__
errread, errwrite)
  File "/usr/lib/python2.5/subprocess.py", line 1002, in
_execute_child
errpipe_read, errpipe_write = os.pipe()
OSError: [Errno 24] Too many open files

Now, up that limit to 8192 via ulimit -n, and run the script again:

[r...@marvin jeff]# ulimit -n 8192
[r...@marvin jeff]# python test.py
[r...@marvin jeff]#

HTH,

Jeff

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


Re: file write collision consideration

2009-01-20 Thread D'Arcy J.M. Cain
On Tue, 20 Jan 2009 10:57:52 -0500
RGK  wrote:
> I have a thread that is off reading things some of which will get 
> written into a file while another UI thread manages input from a user.
> 
> The reader-thread and the UI-thread will both want to write stuff to the 
> same output file. What first comes to mind is that there may be write 
> collisions, ie both trying to write at the same time.

Why not create a third thread that handles the write?  The other
threads can simply add objects to a queue.  You will still need
collision handling in the queue adder but it only needs to block for a
small time as opposed to the much longer disk write time.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: file write collision consideration

2009-01-20 Thread MRAB

RGK wrote:
I have a thread that is off reading things some of which will get 
written into a file while another UI thread manages input from a user.


The reader-thread and the UI-thread will both want to write stuff to the 
same output file. What first comes to mind is that there may be write 
collisions, ie both trying to write at the same time.


Should I do something like:


if busyFlag:
  while busyFlag:
 sleep(10)
else:
  busyFlag = True
  {write stuff to file}
  busyFlag = False


in both threads?   Is there some other approach that would be more 
appropriate?


Thanks in advance for your advice

If you're using the threading module, I suggest you look at the 
threading.RLock class:


my_lock = threading.RLock()
...
with my_lock:
{write stuff to file}

or, if you're using an older version of Python:

my_lock = threading.RLock()
...
my_lock.acquire()
{write stuff to file}
my_lock.release()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in Tkinter - Python 2.6

2009-01-20 Thread José Matos
On Monday 19 January 2009 09:24:09 Eric Brunel wrote:
> This is not the procedure I describe in the original post. The first time,
>   it works for me too. It's only after I used the file dialog that it stops
> working.

You are right, my mistake.

-- 
José Abílio
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pyro deadlock

2009-01-20 Thread J Kenneth King
MatthewS  writes:

> I'd like to know if the following behavior is expected and can be
> avoided: I have a Pyro server object that maintains a queue of work,
> and multiple Pyro worker objects that take work off the queue by
> calling a method on the server (get_work) and then return the work to
> the server by calling another method (return_result).
>
> The problem is that I experience a deadlock condition in the
> return_result method.
>
> Is this deadlock expected or should Pyro be able to synchronize the
> remote calls to server's callback method when called from multiple
> workers at the same time? If so any hints are appreciated.
>
> /Matthew

Depends on how you're implementing the work/result queues.

The Queue module is a good start.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Doubts related to subprocess.Popen()

2009-01-20 Thread Mark Wooding
"Diez B. Roggisch"  writes:

> Usually, each new process has three file-descriptors associated with
> it - stdin,stdout and stderr.
>
> So when you span a process, the overall count of FDs should increase
> by three.

Yes, but that's irrelevant.  There are two file limits which are
relevant:

  * the per-process limit on file descriptors -- basically, the largest
number which can be a file descriptor -- and

  * the overall number of files which can be open at a time.

Note that, in Unix, the same file can be referred to by many different
descriptors in many different processes, and fork(2), exec(2) and dup(2)
don't change the number of files open.  However, dup(2) allocates a new
descriptor in the calling process, so it may hit the per-process limit.

> Additionally, there are more FDs created if you chose to pipe
> communication between the child-process and the parent.

And these are the ones I mentioned.

OK, in more detail: each pipe(2) call allocates two files (one for each
end) and two file descriptors (one for each file).  If you call Popen
with PIPE specified for each of stdin, stdout and stderr, then that's a
total of six descriptors and six files.  But the parent will close half
of them after calling fork(2) (freeing three descriptors), and the child
will close all six after dup2(2)-ing them over the descriptors 0, 1, and
2.  The net result is:

  * six new files in the global file table, and
  * three new descriptors in the parent.

(The child ends up with no new descriptors at the end of all this.)

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: ifconfig in python

2009-01-20 Thread Nehemiah Dacres
I'll let this thought fester but I thought I'd put together a PEP to make
this a function. Possibly in some util library but preferibly in the sys
library sense this is where to get information about the system you are
running on.

On Tue, Jan 20, 2009 at 6:33 AM, Mark Wooding  wrote:

> Дамјан Георгиевски  writes:
>
> > Something *like*  this could work:
> >
> >   myip = 
> > urllib2.urlopen('http://whatismyip.org/').read(
> )
>
> This is going to cause all manner of problems.
>
> Firstly, many users are stuck behind NAT routers.  In this case, the
> external service will report the address of the router, which is
> probably useless -- certainly it will be for programs attempting to
> communicate over a LAN.
>
> Secondly, imagine the joy when overzealous ISPs decide that
> whatismyip.org is peddling kiddiepr0n (as happened to Wikipedia last
> month): then the service will report the address of ISP's censoring
> proxy to thousands of otherwise unrelated users.
>
> And that's before we get onto onion routers like Tor...
>
> Here's an idea which might do pretty well.
>
> In [1]: import socket as S
> In [2]: s = S.socket(S.AF_INET, S.SOCK_DGRAM)
> In [4]: s.connect(('192.0.2.1', 666))
> In [5]: s.getsockname()
> Out[5]: ('172.29.198.11', 46300)
>
> (No packets were sent during this process: UDP `connections' don't need
> explicit establishment.  The network 192.0.2.0/24 is reserved for use in
> examples; selecting a local address should therefore exercise the
> default route almost everywhere.  If there's a specific peer address or
> network you want to communicate with, use that address explicitly.)
>
> I have to wonder what the purpose of this is.  It's much better to have
> the recipient of a packet work out the sender's address from the packet
> (using recvfrom or similar) because that actually copes with NAT and so
> on properly.
>
> -- [mdw]
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 

"lalalalala! it's not broken because I can use it"

http://linux.slashdot.org/comments.pl?sid=194281&threshold=1&commentsort=0&mode=thread&cid=15927703
--
http://mail.python.org/mailman/listinfo/python-list


Re: ifconfig in python

2009-01-20 Thread Mark Wooding
"rasikasriniva...@gmail.com"  writes:

> one way to get your head around this is - IP Addresses are associated
> with the interface and not the computer. distinction may be subtle but
> critical.

Actually this is wrong for most Unix systems, which use the `weak
end-system model' described in RFC1122.  Weak end-systems accept IP
packets sent to any of the host's addresses (and respond to ARP requests
for any address) arriving on any of its interfaces, and might send a
packet from any of the host's addresses out of any interface.  It's best
to think of the addresses as referring to the host, and not the
interfaces.

That doesn't mean that you can get away with a single address for the
entire host, though: you need addresses which correspond to the networks
you're attached to.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: ifconfig in python

2009-01-20 Thread Nehemiah Dacres
>
> That doesn't mean that you can get away with a single address for the
> entire host, though: you need addresses which correspond to the networks
> you're attached to.
>
> -- [mdw]

especially sense we are also getting into virtual NICs where you can have a
webserver listening to one and broadcasting a stream to another.



-- 

"lalalalala! it's not broken because I can use it"

http://linux.slashdot.org/comments.pl?sid=194281&threshold=1&commentsort=0&mode=thread&cid=15927703
--
http://mail.python.org/mailman/listinfo/python-list


Free-test russian xxx site

2009-01-20 Thread metro5

Free-test russian xxx site  http://xxx.gamapa.ru http://xxx.gamapa.ru 
-- 
View this message in context: 
http://www.nabble.com/Free-test-russian-xxx-site-tp21568375p21568375.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Overloading Methods

2009-01-20 Thread K-Dawg
Can you overload methods in Python?

Can I have multiple __inits__ with different parameters passed in?

Thanks.

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


Free-test russian xxx site

2009-01-20 Thread metro5

Free-test russian xxx site  http://xxx.gamapa.ru http://xxx.gamapa.ru 
-- 
View this message in context: 
http://www.nabble.com/Free-test-russian-xxx-site-tp21568438p21568438.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Free-test russian xxx site

2009-01-20 Thread metro5

Free-test russian xxx site  http://xxx.gamapa.ru http://xxx.gamapa.ru 
-- 
View this message in context: 
http://www.nabble.com/Free-test-russian-xxx-site-tp21568445p21568445.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


RE: ifconfig in python

2009-01-20 Thread bruce
so the question really starts to look like:

 -what's the default listening address for my app (insert nic)?
 -what's the default sending address for my app (insert nic)?
 -what's the default listening address for my server?
 -what's the default sending address for my server?
 -what's the default listening address for my (insert nic)?
 -what's the default sending address for my (insert nic)?

any other possibilities??



-Original Message-
From: python-list-bounces+bedouglas=earthlink@python.org 
[mailto:python-list-bounces+bedouglas=earthlink@python.org]on Behalf Of 
Nehemiah Dacres
Sent: Tuesday, January 20, 2009 10:04 AM
To: Mark Wooding
Cc: python-list@python.org
Subject: Re: ifconfig in python





That doesn't mean that you can get away with a single address for the
entire host, though: you need addresses which correspond to the networks
you're attached to.

-- [mdw]
especially sense we are also getting into virtual NICs where you can have a 
webserver listening to one and broadcasting a stream to another. 




-- 

"lalalalala! it's not broken because I can use it"

http://linux.slashdot.org/comments.pl?sid=194281&threshold=1&commentsort=0&mode=thread&cid=15927703

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


Re: English-like Python

2009-01-20 Thread Aaron Brady
On Jan 17, 6:10 pm, The Music Guy  wrote:
> Wow, impressive responses.
>
> It sounds like the general consensus is that English would not be a good
> choice for programming even if there were an interpreter capable of
> turning human language into machine language. But that makes sense; even
> English professionals have trouble understanding each other sometimes.
> Until that problem is somehow overcome, there's not much hope of
> computers to overcome it.

I think it would be a good step if you could make some sensible
interpretation of a typical statement without its parentheses.

f "abc" 123
-->
f( "abc", 123 )

It would be just the thing in a couple of situations... though it does
conflict with raw-string literals as stated: r"abc"... which if you
left open, would be susceptible to a local definition of r!.  Maybe
you could put it after, like numeric literals: 123L, "abc"r, which is
not bad.
--
http://mail.python.org/mailman/listinfo/python-list


RE: Problem with IDLE on windows XP

2009-01-20 Thread Grimes, George
¡Muchas gracias!  That was the hint that I needed, Gabriel.  I had a problem
with my path definition and running idle the way you indicated gave me an
error message saying that it could not find a valid init.tcl on the path.
I have fixed the problem and can now run idle at work.

Thanks again!

George


George A. Grimes
972-995-0190 - Desk
214-205-0244 - Cell

Failure is the opportunity to begin again, more intelligently.
Henry Ford


-Original Message-
From: python-list-bounces+georgegrimes=ti@python.org 
[mailto:python-list-bounces+georgegrimes=ti@python.org] On Behalf Of 
Gabriel Genellina
Sent: Tuesday, January 20, 2009 9:33 AM
To: python-list@python.org
Subject: Re: Problem with IDLE on windows XP

En Mon, 19 Jan 2009 20:50:43 -0200, Grimes, George   
escribió:

> I am trying to learn Python and I installed version 2.6 both at home and  
> at work.  At home, on
> Vista, everything works fine.  At work, on XP, IDLE would not run.  I  
> uninstalled/reinstalled
> and got the same thing.  My cursor changes to the wait symbol for a few  
> seconds, then goes
> back to normal and ….nothing.  The Task Manager shows nothing.  I  
> uninstalled again,
> made sure all the files were deleted from the disk, used regedit to  
> delte every registry entry
> that had python in it and tried version 3.0.
>
> Geuss, what?  I still can’t run IDLE on XP?  Is this a common problem?   
> Or am I unique?

Did you install "for all users" (as Administrator) or "just for me"?

The following instructions assume you installed Python 2.6 on C:\Python26  
-- replace with your own directory if different.

Open a command prompt (go to Start, Run, type "cmd" and press Enter).
At the > prompt type:

c:\Python26\python -V

and press Enter. Should reply with the Python version. Then try with:

c:\Python26\python c:\Python26\Lib\idlelib\idle.pyw

Should start IDLE, probably you get some error message; post it here.

-- 
Gabriel Genellina

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


Free-test russian xxx site

2009-01-20 Thread metro5

Free-test russian xxx site  http://xxx.gamapa.ru http://xxx.gamapa.ru 
-- 
View this message in context: 
http://www.nabble.com/Free-test-russian-xxx-site-tp21568578p21568578.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Overloading Methods

2009-01-20 Thread MRAB

K-Dawg wrote:

Can you overload methods in Python?

Can I have multiple __inits__ with different parameters passed in?


Simple answer: no.
--
http://mail.python.org/mailman/listinfo/python-list


Re: s=str(binary)

2009-01-20 Thread gert
On Jan 20, 5:23 am, John Machin  wrote:
> On Jan 20, 12:54 pm, gert  wrote:
>
> > How do you convert s back to binary data in python 3 so I can put in a
> > sqlite blob ?
> > Is there a build in function or do I need to use binascii ?
> > byte(s) or bin(s) would make more sense but can not figure it out ?
>
> Can't imagine why you would do str(binary_data) especially if you want
> it back again ... however:

def application(environ, response):
s = str(environ['wsgi.input'].read())
b = compile('boundary=(.*)').search(environ['CONTENT_TYPE']).group
(1)
p = compile(r'.*Content-Type: application/octet-stream\\r\\n\\r\\n
(.*)\\r\\n--'+b+'.*'+b+'--', DOTALL).match(s).group(1)
db.execute('UPDATE users SET picture=? WHERE uid=?',
(p,session.UID))

> According to the fabulous manual:
>
> str([object[, encoding[, errors]]])
> Return a string version of an object, using one of the following
> modes:
> [snip]
> When only object is given, this returns its nicely printable
> representation. For strings, this is the string itself. The difference
> with repr(object) is that str(object) does not always attempt to
> return a string that is acceptable to eval(); its goal is to return a
> printable string.
>
> Hmm looks like (1) we need to do the dreaded eval() and (2) there's no
> guarantee it will work.
>
> >>> for i in range(256):
>
> ...    blob = bytes([i])
> ...    if eval(str(blob)) != blob:
> ...       print(i, blob, str(blob), eval(str(blob)))
> ...
>
> >>> # no complaints!
>
> Looks like it's going to work, but you better be rather sure that you
> trust the source.

Any other suggestions ?

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


Re: Overloading Methods

2009-01-20 Thread Chris Rebert
On Tue, Jan 20, 2009 at 10:18 AM, MRAB  wrote:
> K-Dawg wrote:
>>
>> Can you overload methods in Python?
>>
>> Can I have multiple __inits__ with different parameters passed in?
>>
> Simple answer: no.

More complicated answer: Yes, with some caveats.

You usually don't need to overload methods in Python since you can use
default and keyword arguments instead. For instance:

class Foo(object):
def __init__(self, a, b=10, c=None):
self.a = a
self.b = b
if c is None: c = []
self.c = c

#example use
x = Foo("#", 4, [6,7])
y = Foo("@")
z = Foo("!", c=[1,2])

Whereas in Java or C++ this would require several overloads, it can be
succinctly expressed as a single method in Python.

However, if you want the overloads to accept completely different
types as parameters, then it arguably should expressed as distinct
methods rather than "overloads". In the special case of __init__, you
might want to make the alternate initializers classmethods or factory
functions.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: file write collision consideration

2009-01-20 Thread RGK
Thanks for the suggestions - sounds like a couple good options, I 
apprecieate it.


Ross.

MRAB wrote:

RGK wrote:
I have a thread that is off reading things some of which will get 
written into a file while another UI thread manages input from a user.


The reader-thread and the UI-thread will both want to write stuff to 
the same output file. What first comes to mind is that there may be 
write collisions, ie both trying to write at the same time.


Should I do something like:


if busyFlag:
  while busyFlag:
 sleep(10)
else:
  busyFlag = True
  {write stuff to file}
  busyFlag = False


in both threads?   Is there some other approach that would be more 
appropriate?


Thanks in advance for your advice

If you're using the threading module, I suggest you look at the 
threading.RLock class:


my_lock = threading.RLock()
...
with my_lock:
{write stuff to file}

or, if you're using an older version of Python:

my_lock = threading.RLock()
...
my_lock.acquire()
{write stuff to file}
my_lock.release()

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


Re: file write collision consideration

2009-01-20 Thread Francesco Bochicchio
On Tue, 20 Jan 2009 11:08:46 -0500, D'Arcy J.M. Cain wrote:

> On Tue, 20 Jan 2009 10:57:52 -0500
> RGK  wrote:
>> I have a thread that is off reading things some of which will get 
>> written into a file while another UI thread manages input from a user.
>> 
>> The reader-thread and the UI-thread will both want to write stuff to the 
>> same output file. What first comes to mind is that there may be write 
>> collisions, ie both trying to write at the same time.
> 
> Why not create a third thread that handles the write?  The other
> threads can simply add objects to a queue.  You will still need
> collision handling in the queue adder but it only needs to block for a
> small time as opposed to the much longer disk write time.

IIRC, Queue.Queue objects handle by themselves multi-thread access, that
is there is no need to additional locking mechanism ...

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


Re: English-like Python

2009-01-20 Thread Joe Strout

Aaron Brady wrote:


I think it would be a good step if you could make some sensible
interpretation of a typical statement without its parentheses.

f "abc" 123
-->
f( "abc", 123 )

It would be just the thing in a couple of situations...


Such a language is possible -- take a look at REALbasic sometime.  RB 
certainly has its problems (mainly bugs), but the language syntax is 
beautiful.  To your point, parentheses are not required around any 
method call that (1) has no return value, or (2) requires no parameters. 
 Example:


 LogError "Walk has gotten too silly", CurrentTime

Here, LogError is a method call that takes two arguments, and 
CurrentTime is a method call that takes none.


Your "f" example above works fine in RB too, though with such an 
abstract example it's a little hard to see why it's so cool.


Eliminating unnecessary parentheses does a lot to improve the 
readability of the code IMHO.


Cheers,
- Joe

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


Re: SetUp functions for multiple test cases

2009-01-20 Thread brooklineTom
On Jan 20, 9:57 am, Roy Smith  wrote:
> In article
> <45b0bf56-673c-40cd-a27a-62f9943d9...@r41g2000prr.googlegroups.com>,
>  Georg Schmid  wrote:
>
> > I've just started working with unittests and already hit a snag. I
> > couldn't find out how to implement a setup function, that is executed
> > only _once_ before all of the tests. Specifically, I need this for
> > testing my database interface, and naturally I don't want to create a
> > new database in-memory and fill it with example data for every single
> > test case.
>
> Short answer -- there's no way to do it in the unittest framework.
>
> The True Unit Test Zealots will argue that all tests should be 100%
> independent of each other, which means there should be NO common state
> between test cases.  For that matter, they will also argue that unit tests
> should not interface with external resources like databases.  And they're
> right.
>
> On the other hand, the Real World Test Pragmatists will argue that this is
> just not practical in all cases.  Real programs have classes which interact
> with the outside world, and they need to get tested.  You could stub out
> the external resource, but that's a lot of work, and may introduce as many
> problems as it solves.  Sometimes, a big part of what you're testing is
> your understanding of the external world (i.e. "does this really work like
> it's documented?").
>
> Plus, some operations are just too expensive to do for every test case.  I
> don't know how long it takes to build your in-memory database.  If it takes
> one second, it probably makes sense to do it for every test case (unless
> you've got thousands of test cases).  If it takes 10 minutes, then it makes
> sense to do it once and deal with the fact that you're violating True Unit
> Test Dogma.
>
> Anyway, do what I do.  I run the tests with a:
>
> if __name__ == "__main__":
>blah blah
>
> block at the bottom of the test file.  Just do your "do once" setup in that
> code block and store the result in a global.
>
> You might have your setUp() method re-assign the global to an instance
> variable and then your test cases can access it via self.whatever.  The
> reason for that is if at some point in the future you change your mind and
> decide to re-build the database in setUp() for each test, you just have to
> change setUp(), not touch the individual test cases.

I believe that the answer sought by the OP is the TestResource class
from the original Smalltalk unit test. Sadly, the various language-
specific clones -- including the Python unittest package -- followed
the example of the JUnit hack, which elided this (for a variety of
reasons, some good, some bad). There are two major obstacles in moving
SUnit from Smalltalk to Python: (1) SUnit takes full advantage of
class objects which still have only vestigial implementations in
Python, and (2) SUnit takes full advantage of Smalltalk's restartable
exception semantics.

I've implemented an alternative unit test package, but I requires the
rest of my framework (which addresses the above two restrictions) and
is therefore not yet ready for prime time.

The basic theme of TestResource is simple enough, once the rest of the
unit test framework is properly factored:
1. Tests always run within an instance of TestSuite.
2. The "run" method of test suite (with no arguments) collects and
creates whatever resources are needed by the tests within it.
3. The run method creates an instance of TestResult to collect the
results.
4. Each TestCase instance collects whatever (existing) resources it
needs.
5. When the "run" method (in step 2 above) finishes, all resources are
finalized.

Instances of TestResource have a "setUp" and "tearDown" method, just
like TestCase. These are called once, at steps 2 and 5 above.

I built my test frame from the original SUnit from KentBeck et al and
used an excellent reference Joseph Pelrine (http://www.metaprog.com/
ESUG/TestResources.pdf) to guide my work.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-20 Thread Russ P.
On Jan 20, 5:33 am, Luis Zarrabeitia  wrote:
> On Tuesday 20 January 2009 05:00:34 am Paul Rubin wrote:
>
> > Luis Zarrabeitia  writes:
> > > No wonder you can't get Bruno's point. For the second, static checks
> > > to prevent accidents, you have pylint. For the first, not only you
> > > are using the wrong tool, but you are barking at python for not
> > > having it. Assuming that pylint is perfect (big assumption, but it
> > > is up to you to prove where it fails),
>
> > Whaat?  Assuming a program is perfect unless a failure is proven
> > is not at all a sane approach to getting reliable software.  It is
> > the person claiming perfection who has to prove the absence of failure.
>
> No, no. I meant that if pylint works as its specification says it would.
>
> Russ says (or seems to say, I don't know, I'm confused already) that it is not
> good enough, that what pylint says it does is not what he wants (otherwise,
> this subthread would have died a long time ago). So, assuming that pylint
> works as specified (its up to "you" to find out if it doesn't and file
> bugreports about it, just like you would do if you find out that the
> static-checker for your enforced-static-checks-language is buggy), what
> would be the difference between only accepting/running "pylint-authorized
> code" and the enforced hiding you desire?
>
> Sorry, I didn't realize that perfect was a too strong word for that. "I speaks
> english bad" :D
>
> Cya!
>
> --
> Luis Zarrabeitia (aka Kyrie)
> Fac. de Matemática y Computación, UH.http://profesores.matcom.uh.cu/~kyrie


Hey, if pylint can reliably detect private data access violations,
that's good news to me. I haven't used it, so I don't know. (I used
pychecker a while back, but I haven't used that for a while either.)

If pylint can check access violations, then it seems to me that
someone (who is familiar with the internals of the Python interpreter)
should be able to integrate that feature into Python itself relatively
easily.

Actually, in addition to the enforcement of "private," you also need
the enforcement of "protected." If you only enforce "private," derived
classes will not have access to data they need. And if you don't
enforce "protected," then anyone can trivially gain access to private
data by simply deriving a new class. It would be like having a lock on
the door with the key hanging right there on a string.

I realize that this complicates matters. As I said before, I am not
claiming that Python should necessarily get enforced data hiding. All
I am saying is that, if it doesn't get it, it will never be
appropriate for certain domains. But maybe nobody cares about that
except me.

The other problem with the pylint approach is aesthetic: the
requirement for a leading underscore to indicate private data. I
realize that some actually like that convention, but I don't. I spend
most of my development time working with "private" data, and why
should I have to look at that litter everywhere? I use Python in part
because I want clean looking code, and leading underscores bother me
-- just as the leading dollar signs in Perl bother many Python
programmers.
--
http://mail.python.org/mailman/listinfo/python-list


Re: English-like Python

2009-01-20 Thread Abah Joseph
Python is English-like enough that everybody including non-programmers can
understand it.e.g

# Import the operating system module
import os

# define new function
def open_dir_tree(path):
for File in os.listdir(path):
file_or_dir = os.path.join(path, File)
# Read the line below, this is almost full english language
if os.path.isdir(file_or_dir) and not os.path.islink(file_or_dir):
open_dir_tree(file_or_dir)
else:
print file_or_dir
open_dir_tree(".")




-- 
I develop dynamic website with PHP & MySql, Let me know about your site
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get first/last day of the previous month?

2009-01-20 Thread John Machin
On Jan 21, 2:07 am, Marco Mariani  wrote:
> Carsten Haese wrote:
> > In order to not deprive you of the sense of accomplishment
>
> Sorry for spoiling that. If you still want the sense of accomplishment,
> try to reimplement dateutil (and rrule). It's not as easy as it seems :-o

True, but getting the last day of a given month from first principles
without any library routines is nowhere near as complex as (e.g.)
converting (y,m,d) <-> ordinal day number.

It's this easy:

# days in month (non-leap year)
_dim = (None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

def _leap(y):
if y % 4: return 0
if y % 100: return 1
if y % 400: return 0
return 1

def last_day_of_month(y, m):
"""Return day (1..31) which is last day of month m in year y
"""
if m == 2:
return 28 + _leap(y)
if not (1 <= m <= 12):
raise Exception("month not in 1..12")
return _dim[m]

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


Re: python resource management

2009-01-20 Thread S.Selvam Siva
On Tue, Jan 20, 2009 at 7:27 PM, Tim Arnold  wrote:

> I had the same problem you did, but then I changed the code to create a new
> soup object for each file.That drastically increased the speed.  I don't
> know why, but it looks like the soup object just keeps getting bigger with
> each feed.
>
> --Tim
>
> I have found the actual solution for this problem.
I tried using *BeautifulSoup.SoupStrainer()* and it improved memory
usage to the
greatest extent.Now it uses max of 20 MB(earlier
it was >800 MB on 1GB RAM system).
thanks all.



-- 
Yours,
S.Selvam
--
http://mail.python.org/mailman/listinfo/python-list


Re: English-like Python

2009-01-20 Thread Aaron Brady
On Jan 20, 12:58 pm, Joe Strout  wrote:
> Aaron Brady wrote:
> > I think it would be a good step if you could make some sensible
> > interpretation of a typical statement without its parentheses.
>
> > f "abc" 123
> > -->
> > f( "abc", 123 )
>
> > It would be just the thing in a couple of situations...
>
> Such a language is possible -- take a look at REALbasic sometime.  RB
> certainly has its problems (mainly bugs), but the language syntax is
> beautiful.  To your point, parentheses are not required around any
> method call that (1) has no return value, or (2) requires no parameters.
>   Example:
>
>   LogError "Walk has gotten too silly", CurrentTime
>
> Here, LogError is a method call that takes two arguments, and
> CurrentTime is a method call that takes none.
>
> Your "f" example above works fine in RB too, though with such an
> abstract example it's a little hard to see why it's so cool.
>
> Eliminating unnecessary parentheses does a lot to improve the
> readability of the code IMHO.
>
> Cheers,
> - Joe

Unambiguity and readability are two different things.  (This should be
a quasi-tangent, neither agreed, nor opposed, nor unrelated to what
you said.)

If you have

f "abc" 123

it's unambiguous, but, if you have

g f "abc" 123 "def"

there's no sure way to determine where the call to 'f' stopped, and
the one to 'g' resumed (or, as in Python, if 'f' was even to be called
at all, as opposed to 4 parameters to 'g').

If you allow commas, you can make some progress, though I don't have a
rigorous formula.  But, for example,

g f "abc", 123 "def"

can only mean:

g( f( "abc", 123 ), "def" )

But something tells me it doesn't extend, especially since commas are
used elsewhere than function calls.  And certainly, it's not readable
at a glance.

English has that problem and kind of glaringly, by the way.  You don't
always know how the speaker's subordinate clauses are nesting.  Not
just with clauses, but modifiers, as in "The Purple People Eater".  So
I don't know how you expect to design a programming language after it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ifconfig in python

2009-01-20 Thread Mark Wooding
"bruce"  writes:

[a top-posted monstrosity]

> so the question really starts to look like:
>
>  -what's the default listening address for my app (insert nic)?
>  -what's the default sending address for my app (insert nic)?
>  -what's the default listening address for my server?
>  -what's the default sending address for my server?
>  -what's the default listening address for my (insert nic)?
>  -what's the default sending address for my (insert nic)?
>
> any other possibilities??

A TCP server will typically listen on:

  * all addresses (INADDR_ANY),
  * localhost (INADDR_LOOPBACK), or
  * an address explicitly provided by the administrator.

(There's a fourth possibility: it might listen separately on each
network interface, but that's quite unusual.)  Anyway, it ought to know
which of these it's doing.  When a client connects, it gets the client's
address from accept(2) or getpeername(2) and its local address from
getsockname(2).

A TCP client can find out its address using getsockname(2) after
connect(2).  So that's easy too.

But TCP isn't very interesting here, because both ends know the others'
address by the time the connection is established, so there's no point
in explicitly sending them.  (I suppose you could use explicit addresses
to detect NAT routers which aren't doing protocol-specific bodging.)

UDP is much messier, since a single socket could be acting as a client
or server, or in a strictly symmetrical arrangement.  Even so, it's
usually much better to have the hosts concerned dredge out their peers'
addresses from the packets they receive rather than send them about
explicitly.

Which is why I'm puzzled as to what this information is actually for.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: English-like Python

2009-01-20 Thread Joe Strout

Aaron Brady wrote:


Unambiguity and readability are two different things.  (This should be
a quasi-tangent, neither agreed, nor opposed, nor unrelated to what
you said.)

If you have

f "abc" 123

it's unambiguous, but, if you have

g f "abc" 123 "def"

there's no sure way to determine where the call to 'f' stopped, and
the one to 'g' resumed (or, as in Python, if 'f' was even to be called
at all, as opposed to 4 parameters to 'g').


Right -- that's exactly why (in RB) parentheses are required around 
arguments to a method call if that method returns a value (in RB terms, 
if it is a function rather than a subroutine).  Then there is no 
ambiguity, because only such a function can be used as an argument to 
another method call (or otherwise be part of an expression).  The above 
would have to be written something like:


 g f("abc", 123), "def"

I'm not saying I know how to translate this into Python -- some of 
Python's other language features make this difficult.  Just pointing out 
that your original wish is possible in at least some languages.


Best,
- Joe


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


Re: what's the point of rpython?

2009-01-20 Thread Brendan Miller
On Tue, Jan 20, 2009 at 3:46 AM, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> s...@pobox.com writes:
>> Carl, I'm quite unfamiliar with Boost and am not a C++ person, so may have
>> read what you saw but not recognized it in the C++ punctuation soup.  I
>> couldn't find what you referred to.  Can you provide a URL?
>
> http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety

I think you are misreading that. It says that multiple assignments to
different copies of a share_ptr in different threads are fine. This is
the important bit because copies of the same pointer share the same
reference count, and assignments and resets will decrement that ref
count. They say they don't handle mutations of the *same* pointer in
different threads, which is a different issue.

The programmer is responsible for synchronizing access to the pointer,
and the pointed to object, but not the ref count. This may be not be
obvious if you don't use shared_ptr a lot.

You also mentioned in an earlier post that most processors don't
support automic increments... I'm hesitant to dispute you here because
this is outside of my field of expertise. However, a quick google
search for "x86 atomic increment" comes up with this:

XADD

http://www.codemaestro.com/reviews/8
http://siyobik.info/index.php?module=x86&id=159

Again, I'm not an assembly guru, but his sounds like exactly what
you'd want. It gains exclusive access to system memory in a
multi-processor environtment without leaving user space. Thus XADD is
an atomic increment/decrement. It would be educational if someone more
famliar with x86 than me could speak to the performance merits of this
on modern multicore machines.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-20 Thread Rhamphoryncus
On Jan 20, 12:04 pm, "Russ P."  wrote:
 Hey, if pylint can reliably detect private data access violations,
> that's good news to me. I haven't used it, so I don't know. (I used
> pychecker a while back, but I haven't used that for a while either.)
>
> If pylint can check access violations, then it seems to me that
> someone (who is familiar with the internals of the Python interpreter)
> should be able to integrate that feature into Python itself relatively
> easily.
>
> Actually, in addition to the enforcement of "private," you also need
> the enforcement of "protected." If you only enforce "private," derived
> classes will not have access to data they need. And if you don't
> enforce "protected," then anyone can trivially gain access to private
> data by simply deriving a new class. It would be like having a lock on
> the door with the key hanging right there on a string.
>
> I realize that this complicates matters. As I said before, I am not
> claiming that Python should necessarily get enforced data hiding. All
> I am saying is that, if it doesn't get it, it will never be
> appropriate for certain domains. But maybe nobody cares about that
> except me.

If pylint had "private" it should behave like "protected".  Basic
encapsulation is about good style (separation of concerns), not
security, and subclassing is a clear statement that this concern is
closely related.

Of course if you accept that the extremism of security is a separate
issue then you have the question of how much is necessary to encourage
separation of concerns, and and what should be available to work
around it...


> The other problem with the pylint approach is aesthetic: the
> requirement for a leading underscore to indicate private data. I
> realize that some actually like that convention, but I don't. I spend
> most of my development time working with "private" data, and why
> should I have to look at that litter everywhere? I use Python in part
> because I want clean looking code, and leading underscores bother me
> -- just as the leading dollar signs in Perl bother many Python
> programmers.

There needs to be *some* indicator that separates a public property
from a private one.  What would you suggest?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading Methods

2009-01-20 Thread K-Dawg
Thank you for the explanation.  With my background in Java, I have to get
myself to think a little differently.
Kevin


On Tue, Jan 20, 2009 at 1:41 PM, Chris Rebert  wrote:

> On Tue, Jan 20, 2009 at 10:18 AM, MRAB  wrote:
> > K-Dawg wrote:
> >>
> >> Can you overload methods in Python?
> >>
> >> Can I have multiple __inits__ with different parameters passed in?
> >>
> > Simple answer: no.
>
> More complicated answer: Yes, with some caveats.
>
> You usually don't need to overload methods in Python since you can use
> default and keyword arguments instead. For instance:
>
> class Foo(object):
>def __init__(self, a, b=10, c=None):
>self.a = a
>self.b = b
>if c is None: c = []
>self.c = c
>
> #example use
> x = Foo("#", 4, [6,7])
> y = Foo("@")
> z = Foo("!", c=[1,2])
>
> Whereas in Java or C++ this would require several overloads, it can be
> succinctly expressed as a single method in Python.
>
> However, if you want the overloads to accept completely different
> types as parameters, then it arguably should expressed as distinct
> methods rather than "overloads". In the special case of __init__, you
> might want to make the alternate initializers classmethods or factory
> functions.
>
> Cheers,
> Chris
>
> --
> Follow the path of the Iguana...
> http://rebertia.com
>  --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's the point of rpython?

2009-01-20 Thread Ross Ridge
Carl Banks   wrote:
>I just looked at the boost documentation, which claims that multiple
>asynchronous writes to the same shared_ptr results in undefined
>behavior.  That will not suffice for Python reference counting.

If you read the Boost documentation you'll see that while multiple
simulaneous writes to a shared_ptr *instance* isn't supported, multiple
simulataneous updates of the reference counter used by the shared_ptr
implementaiton is supported.  Example #1 in the URL that Paul Rubin
gave demonstrates this.  The allowed simulanteous assignment of the two
shared_ptr instances "p2" and "p3" from the same shared_ptr instance
"p", requires that a single reference count be incremented simultenously.

On the other hand, the documentation also notes that the implementation
is only lock free on x86, IA-64, and PowerPC systems, though I think it
would also be possible on MIPS CPUs.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  rri...@csclub.uwaterloo.ca
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading Methods

2009-01-20 Thread Chris Rebert
(top-posting just for consistency)

In that case, you might also be interested in:
http://dirtsimple.org/2004/12/python-is-not-java.html

Cheers,
Chris

On Tue, Jan 20, 2009 at 12:19 PM, K-Dawg  wrote:
> Thank you for the explanation.  With my background in Java, I have to get
> myself to think a little differently.
> Kevin
>
>
> On Tue, Jan 20, 2009 at 1:41 PM, Chris Rebert  wrote:
>>
>> On Tue, Jan 20, 2009 at 10:18 AM, MRAB  wrote:
>> > K-Dawg wrote:
>> >>
>> >> Can you overload methods in Python?
>> >>
>> >> Can I have multiple __inits__ with different parameters passed in?
>> >>
>> > Simple answer: no.
>>
>> More complicated answer: Yes, with some caveats.
>>
>> You usually don't need to overload methods in Python since you can use
>> default and keyword arguments instead. For instance:
>>
>> class Foo(object):
>>def __init__(self, a, b=10, c=None):
>>self.a = a
>>self.b = b
>>if c is None: c = []
>>self.c = c
>>
>> #example use
>> x = Foo("#", 4, [6,7])
>> y = Foo("@")
>> z = Foo("!", c=[1,2])
>>
>> Whereas in Java or C++ this would require several overloads, it can be
>> succinctly expressed as a single method in Python.
>>
>> However, if you want the overloads to accept completely different
>> types as parameters, then it arguably should expressed as distinct
>> methods rather than "overloads". In the special case of __init__, you
>> might want to make the alternate initializers classmethods or factory
>> functions.
>>
>> Cheers,
>> Chris
>>
>> --
>> Follow the path of the Iguana...
>> http://rebertia.com
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's the point of rpython?

2009-01-20 Thread Rhamphoryncus
On Jan 16, 5:37 pm, "Brendan Miller"  wrote:
> So I kind of wanted to ask this question on the pypy mailing list..
> but there's only a pypy-dev list, and I don't want to put noise on the
> dev list.
>
> What's the point of RPython? By this, I don't mean "What is RPython"?
> I get that. I mean, why?

There are some distinct benefits of RPython:

* starts up as real python code, letting you define globals that later
get "snapshotted" into static code
* can be executed using a real python interpreter, getting much more
reliable debugging (but broken rpython code might run fine under
python)
* provides a clear avenue for extension, by adding more python
features

You might argue just having a python syntax is also a benefit, but the
semantics are so different as to more than counteract it.  Add in the
cost of implementing your own compiler... yeah.
--
http://mail.python.org/mailman/listinfo/python-list


Re: s=str(binary)

2009-01-20 Thread John Machin
On Jan 21, 5:31 am, gert  wrote:
> On Jan 20, 5:23 am, John Machin  wrote:
>
> > On Jan 20, 12:54 pm, gert  wrote:
>
> > > How do you convert s back to binary data in python 3 so I can put in a
> > > sqlite blob ?
> > > Is there a build in function or do I need to use binascii ?
> > > byte(s) or bin(s) would make more sense but can not figure it out ?
>
> > Can't imagine why you would do str(binary_data) especially if you want
> > it back again ... however:
>
> def application(environ, response):
>     s = str(environ['wsgi.input'].read())
>     b = compile('boundary=(.*)').search(environ['CONTENT_TYPE']).group
> (1)
>     p = compile(r'.*Content-Type: application/octet-stream\\r\\n\\r\\n
> (.*)\\r\\n--'+b+'.*'+b+'--', DOTALL).match(s).group(1)
>     db.execute('UPDATE users SET picture=? WHERE uid=?',
> (p,session.UID))
>
[snip]
>
> > Looks like it's [it being eval(str(blob))] going to work, but you better be 
> > rather sure that you
> > trust the source.
>
> Any other suggestions ?

Yeah.

(a) don't write obfuscatory code :-0

E.g.
(1) re.compile(pattern).search(data) -> re.search(pattern, data)
(2) re.compile(pattern).match(data) -> re.match(pattern, data)
(3) re.match('.*blahblah', data) -> re.search('blahblah', data)

(b) don't use re when ordinary str or bytes methods will do

E.g. instead of:
b = re.search('boundary=(.*)'), environ['CONTENT_TYPE']).group(1)
try
b = environ['CONTENT_TYPE'].split('boundary=')[1]

(c) Is that code meant to be rough pseudocode to illustrate what you
are trying to do, or is it meant to be working code? If the latter:
* Do you have this working in 2.X?
* Are you sure the pattern to retrieve the picture is correct?
* What is the "Content-Transfer-Encoding"?

(d) Surely there must be a library somewhere that parses that kind of
data for you ...

(e) if all else fails, I'd suggest:

instead of s = str(binary)
do s = binary.decode('latin1')
# this won't change the number of characters and will allow
# reconstitution of your non-ascii bytes
Then do your DIY parsing
then at the end do
blob = p.encode('latin1')
# blob will be type bytes which is presumably what the database
expects

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


Re: python processes and Visual Studio

2009-01-20 Thread bill
On Jan 19, 9:24 am, bill  wrote:
> All,
>
> This may sound somewhat convoluted, but here goes:
>
> 1. I have a Python script that invokes builds in Visual Studio via the
> command line interface - 'devenv'
> 2. It works GREAT
> 3. I have added a post_build event to a VS Solution that has but one
> project.
> 4. This event invokes a Python command - 'c:\python25\python.exe c:
> \myPython.py'
> 5. It works GREAT
> 6. I move on the another VS Solution that has 6 projects.
> 7. I add the post_build event command to all 6 projects
> 8. It 'almost' works... all 6 projects build and the post_build event
> triggers in all 6 projects and that works
> 9. Unhappily, the whole thing then 'hangs'
>
> I am guessing that perhaps a sub-process or something like that is not
> exiting. The Python script that is triggered in the post_build event,
> myPython.py, does nothing special upon exit. Should it?
>
> Or, is there some way to determine why the the while thing 'hangs'?
>
> TIA,
>
> Bill

All,

Please ignore this post (if you already haven't). Whatever the problem
is, it has absolutely nothing to do with Python.

Sorry about that
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's the point of rpython?

2009-01-20 Thread Rhamphoryncus
On Jan 19, 9:00 pm, "Brendan Miller"  wrote:
> Maybe I'm missing something here but a lock free algorithm for
> reference counting seems pretty trivial. As long as you can atomically
> increment and decrement an integer without locking you are pretty much
> done.

"lock free" is largely meaningless.  What it really means is "we use
small hardware locks rather than big software locks, thereby reducing
(but not eliminating!) the contention".

Atomic refcounting is easy.  If done sparingly to minimize contention
it works great.  Python uses refcounting massively with heavily
contended objects (think about your builtin types, constants, globals,
classes, etc.)  It does not perform acceptably for python.

The second issue is the objects themselves, like a list which is
mutable.  If you're using it in a single thread or writing from
multiple threads this is a non-trivial constant cost.  If your object
is not modified after creation and is read from many threads a lock
would be a point of contention, preventing you from scaling freely.
The dicts used by classes and globals are an import example of this,
and a successful implementation needs something non-contending.  I
assume Jython and IronPython do this.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >