Re: How to tell when a socket is closed on the other end?

2007-07-25 Thread Roy Smith
In article [EMAIL PROTECTED],
 billiejoex [EMAIL PROTECTED] wrote:

 Hi there.
 I'm setting up test suite for a project of mine.
 From test suite, acting as a client, I'd like to know, in certain
 situations, if the socket is closed on the other end or not.
 I noticed that I can detect such state if a call to socket.read()
 returns 0 but it seems a little poor to me. :-\
 Is there a reliable way to test such socket 'state'?

This isn't really a Python question, it's a Berkeley Socket API question.  
You don't say, but I assume you're talking about a TCP (i.e. SOCKSTREAM) 
connection?

The answer is you can use the select() system call to detect exceptional 
conditions on a socket.  Python's select module provides this 
functionality, but to understand how to use it, you need to study the 
underlying API.

On the other hand, socket.read() returning 0 works too.  What do you find 
poor about that?  What do you want to know about the connection being 
closed that you don't find out by getting 0 back from read()?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to tell when a socket is closed on the other end?

2007-07-26 Thread Roy Smith
Jay Loden [EMAIL PROTECTED] wrote:

 The goal of this 
 portion of the test suite we are writing for the project is to determine if a 
 remote server is behaving properly by closing a socket from the server side 
 based on a client-side command.
 
 Really what's needed is a way to make sure the socket gets closed, and 
 preferably determine if it was closed from the remote end as expected.

This really is way out of scope for a Python newsgroup, but what the heck.  
There is no way to tell through the Socket API *why* the connection was 
shut down, because this information isn't transmitted by the TCP protocol.  
All you know is that the connection did indeed get shut down.  

It could be because the user code at the remote end called close().  Or, it 
could be because the process exited (normally or abnormally) and the kernel 
closed the connection as part of the cleanup.  All the TCP stack at this 
end knows is it got a packet with the FIN bit set.

If you really want to know if the other end completed normally, you need to 
design your user-level protocol to include some end of session 
indication.  For example:

 bash-3.2$ telnet mx.panix.com smtp
 Trying 166.84.1.72...
 Connected to mx.panix.com.
 Escape character is '^]'.
 220 mail1.panix.com ESMTP Postfix
 helo foo
 250 mail1.panix.com
 quit
 221 Bye
 Connection closed by foreign host.

The SMTP user-level protocol sent 221 Bye, then, my telnet client saw the 
actual TCP connection close, and printed the Connection closed by foreign 
host message.  I know the remote end closed down the connection normally 
because I saw the 221 message in response to my quit command.

 Do you 
 know if this is possible to determine from the client side 
 reliably/accurately? Would select()'s exceptional condition flag actually 
 indicate whether or not the root cause of the condition was a socket closed 
 by the remote peer? I've read through the select's manpage and I can't seem 
 to find a reference that indicates what the possible values are for the I/O 
 descriptor sets returned by select. Is there another man page, or a place in 
 the header file for select I can look?

You need to read up about how TCP/IP works.  A good place to start might be 
the Wikipedia article on Transmission Control Protocol.  The canonical 
textbook on the subject would be:

Richard Stevens
UNIX Network Programming, Volume 1, Second Edition:
Networking APIs: Sockets and XTI
Prentice Hall
1998
ISBN 0-13-490012-X
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test driven development

2008-01-24 Thread Roy Smith
In article 
[EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 So my question is when approaching a project that you want to employ
 test driven development on how and where do you start? And also if
 anyone uses top-down design with TDD I would be interested in how you
 do it (does it involve lots of mock objects/ is the first test you
 write the last one to pass)?

I've been a big fan of TDD for a few years.

I don't always use it.  When working with legacy code, sometimes the pain 
of getting things into a test harness exceeds the effort I'm able or 
willing to put into it right now.  The other times I don't use it is when 
I'm just doing some simple little thing (which inevitably grows into 
something bigger than originally anticipated).  In all cases, I often find 
that code I ended up writing is less well documented, less well tested, and 
more buggy.

You've hit the nail on the head with the top-down, bottom-up issue.  TDD 
(at least in my mind) encourages bottom-up design, because it forces you to 
have working code on day one.  This is not always good.  So, the key (as 
you pointed out) to mixing TDD with top-down, is to use mock objects a lot.  
But, this is a good thing; it forces you to write classes which can be 
tested in isolation.  This no only makes for better tested code, but often 
leads to cleaner design.

Now, to drag this thread back to something apropos to Python, the good news 
is that Python makes it easy to work with mock objects.  Often, all you 
need to do is import myTestingFoo as Foo and it all just works.  Since 
functions and classes are first-class objects, it's easy to pass them 
around.  Since Python uses duck typing, you don't have to make sure your 
test class inherets from anything in particular.  It all just works.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Standardization: Wikipedia entry

2008-01-27 Thread Roy Smith
In article 
[EMAIL PROTECTED],
 ajaksu [EMAIL PROTECTED] wrote:

 On Jan 27, 10:32 pm, Paddy [EMAIL PROTECTED] wrote:
  I would value the opinion of fellow Pythoneers who have also
  contributed to Wikipedia, on the issue of Is Python Standardized.
  Specifically in the context of this table:
   http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Gene...
(Comparison of programming languages)
  And this entry in the talk page
   http://en.wikipedia.org/wiki/Talk:Comparison_of_programming_languages...
(Talk:Comparison of programming languages#Standardized Python?)
 
  - Thanks.
 
 Hmmm. Seems to me that Is X Standardized in the given context means
 having a formal, published standard issued by some Standards
 organization.

That's exactly what it means.  For example, if I'm buying a C++ compiler, I 
can specify in the contract, Must comply with ISO 14882, and everybody 
will know what I'm talking about.

On the other side of the fence, if I'm a free-lance C++ developer, I can 
specify to my customers that the code I write will work properly when 
compiled with a compiler that meets ISO 14882.  Whether such a compiler 
actually exists, is besides the point :-)

Python has no such standard.  Sure, there's the stuff on docs.python.org, 
but it's kind of hard to write a contract which says, Must comply with the 
stuff on docs.python.org, and have it be meaningful in a legal sense.

So, I think the No in the Standardized? column for python is exactly 
right.  That's not to say you can't have something good which isn't 
standardized.  Sometimes standards committees even go off into left field 
and field break stuff in the process of standardizing it.  Some things have 
so many different standards (i.e. the pletora of unix standards), it's 
almost worthless to say it's standardized.  But, as it stands, the 
Wikipedia article is correct.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Standardization: Wikipedia entry

2008-01-28 Thread Roy Smith
In article [EMAIL PROTECTED],
 Terry Reedy [EMAIL PROTECTED] wrote:

 Paddy [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 |I would value the opinion of fellow Pythoneers who have also
 | contributed to Wikipedia, on the issue of Is Python Standardized.
 
 Depends entirely on the operative meaning of standardized.  Formal 
 standards body? Obviously no.
 
 Specified in a standard-setting document? Yes.  In fact, in someways, 
 Python is better standardized that C, for instance, in that the Python 
 standard usefully standardizes some things that the C standard leaved 
 unstandardized as 'implementation defined'.
 
 Example 1. Order of evaluation of function arguments.  Python: left to 
 right.  C: undefined (and unstandardized), I believe.
 
 Example 2: Strings for Infinity and Not-A-Number.  Python: will standardize 
 in 2.6 to hide the variation in C implementations (or is Microsoft just 
 non-compliant here?). 

But, surely Python has plenty of implementation defined aspects. 
Especially in the libraries.  Especially those parts of the libraries which 
are thin layers on top of operating system services (os and socket come to 
mind as two highly variable areas).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Standardization: Wikipedia entry

2008-01-29 Thread Roy Smith
In article [EMAIL PROTECTED],
 Terry Reedy [EMAIL PROTECTED] wrote:

 Roy Smith [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 | But, surely Python has plenty of implementation defined aspects.
 | Especially in the libraries.
 
 I personally do not consider the libraries as part of the language (as 
 opposed to the distribution) and was not referring to them.

I realize that there is a difference between the core language and the 
libraries, but Python depends on the libraries more than a lot of other 
languages do.  They are the batteries included part.

Indeed, there is a lot of stuff in the Python Library Reference which in 
most languages would be considered part of the core.  The description of 
boolean operations (and, or, not), for example.  String, sequence, and 
dictionary methods.  Where do you draw the line and say, The core language 
ends here; the rest is just libraries?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does anyone else use this little idiom?

2008-02-02 Thread Roy Smith
In article 
[EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 Ruby has a neat little convenience when writing loops where you don't
 care about the loop index: you just do n.times do { ... some
 code ... } where n is an integer representing how many times you want
 to execute some code.
 
 In Python, the direct translation of this is a for loop.  When the
 index doesn't matter to me, I tend to write it as:
 
 for _ in xrange (1,n):
some code
 
 An alternative way of indicating that you don't care about the loop
 index would be
 
 for dummy in xrange (1,n):
some code
 
 But I like using _ because it's only 1 character and communicates well
 the idea I don't care about this variable.

Not to me.  If I read for _ in ..., I wouldn't be quite sure what _ was.  
Is it some magic piece of syntax I've forgotten about?  Or something new 
added to language while I wasn't paying attention (I still consider most 
stuff added since 1.5 to be new-fangled :-)).  If I see dummy, I know it 
means, the language requires a variable here, but the value is not needed.

 1. It might be a little jarring to people not used to it.  I do admit
 it looks pretty strange at first.
 
 2. The variable _ has special meaning at the interactive interpreter
 prompt.  There may be some confusion because of this.

Wow, I didn't even know about #2.  Now you see what I mean about some 
magic syntax?  Surely, between, It looks strange, and there may be some 
confusion, that's enough reason not to use it?

But, more to the point, I'd try to find variable name which described why I 
was looping, even if I didn't actually use the value in the loop body:

for number_that_you_shall_count_to in xrange(3):
   print Whaaa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Written in C?

2008-07-20 Thread Roy Smith
In article 
[EMAIL PROTECTED],
 Mensanator [EMAIL PROTECTED] wrote:

 C isn't a high level language, that's part of its problem.

C is the highest level assembler language I've ever used.  And I've used a 
few.  It really is cool that you can add two 32-bit integers and not have 
to worry about all those carry bits.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Insert string into string

2008-07-26 Thread Roy Smith
In article [EMAIL PROTECTED],
 Francesco Pietra [EMAIL PROTECTED] wrote:

 I am posting ex novo as it became confusing to me. I take the
 opportunity to ask advice for a second problem.
 
 FIRST PROBLEM
 For file xxx.pdb, insert letter A into each line that starts with
 ATOM. A should be inserted at position 22, i.e., one space after
 LEU, leaving all other characters at the same position as in the
 original example:
 
 
 ATOM  1  N   LEU 1 146.615  40.494 103.776  1.00 73.04   1SG  
  2
 
 In all lines starting with ATOM, LEU is constant as to position
 only (18-20), i.e., LEU may be replaced by
 three different uppercase letters. Therefore, the most direct
 indication would be position 22. If specifying line starting with
 ATOM makes complication, forget about that as most lines begin with
 ATOM so that hand correction will be easy.
 
 Script
 f = open(xxx.pdb, w)
 import sys
 
 for line in sys.stdin:
 line = line[:22] + A + line[23:]
 sys.stdout.write(line)

You're opening xxx.pdb for writing, but then not writing to it.  You're 
writing to stdout.

BTW, you might want to take a look at http://biopython.org.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [unittest] Run setUp only once

2008-07-29 Thread Roy Smith
In article [EMAIL PROTECTED],
 Nikolaus Rath [EMAIL PROTECTED] wrote:

 But at least this variation doesn't work, because unittest apparently
 also creates two separate TwoTests instances for the two tests. Isn't
 there some way to convince unittest to reuse the same instance instead
 of trying to solve the problem in the test code itself?

Nope.  It's a fundamental part of the Xunit design that every test gets a 
complete, virgin environment in which to run.

The sample code that Jean-Paul gave you:

class TwoTests(unittest.TestCase):
setUpResult = None

def setUp(self):
if self.setUpResult is None:
self.setUpResult = computeIt()

does indeed create two instances of TwoTests, but it only calls computeIt() 
once, into which (presumably) all the expensive stuff has been refactored.  

This is, of course, a violation of the rule that says each test must run in 
a clean environment, but if you want to violate that rule, that's up to 
you.  Presumably you know your system and have made an informed decision as 
a consenting adult that you understand the risks and this is what you want 
to do.

Another variation on this would be to take this code out of setUp(), and 
instead create a singleton class (there's a good recipe for this on active 
state) which does your shared setup.  Then in the two tests which need 
this, explicitly call the singleton factory.  I think this is a little 
cleaner than Jean-Paul's way, because at least it isolates the shared stuff 
to exactly the two tests which need it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python String Immutability Broken!

2008-08-24 Thread Roy Smith
In article [EMAIL PROTECTED],
 Hendrik van Rooyen [EMAIL PROTECTED] wrote:

 It is reputed to belong to a programmer who was flayed alive

Reminds me of that great old song from Saturday Night Hacker:

Oh, oh, oh, oh.
Flaying alive, flaying alive.
Oh, oh, oh, oh.
Flaying ali-i-i-i-i-ive!
--
http://mail.python.org/mailman/listinfo/python-list


Re: [1,2,3] exactly same as [1,2,3,] ?

2008-08-29 Thread Roy Smith
Terry Reedy [EMAIL PROTECTED] wrote:
 Yes, so you can write something like either your second example or
 
 l = [
kjasldfjs,
kjsalfj,
ksjdflasj,
 ]
 
 and insert items without worrying about leaving out the comma (less of a 
 problem with 'horizontal' list), or delete the last line and not have to 
 worry about deleting the comma on the line before.

Exactly.  This is one of those little pieces of syntactic sugar which makes 
python so nice to work with.  The alternative is (in C, for example) 
abominations like this:

const char* l[] = {foo
 , bar
 , baz
 };

and even those are not quite as good because you still have to special-case 
the first entry.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [1,2,3] exactly same as [1,2,3,] ?

2008-08-29 Thread Roy Smith
In article [EMAIL PROTECTED],
 Grant Edwards [EMAIL PROTECTED] wrote:

 On 2008-08-29, Roy Smith [EMAIL PROTECTED] wrote:
 
  Exactly.  This is one of those little pieces of syntactic
  sugar which makes python so nice to work with.  The
  alternative is (in C, for example) abominations like this:
 
  const char* l[] = {foo
   , bar
   , baz
   };
 
  and even those are not quite as good because you still have to
  special-case the first entry.
 
 It's probably a spec violation, but I've never seen a C
 compiler that objected to a comma after the last item in an
 initializer list.  (At least not at the warning levels I use,
 which tend to be on the picky side.)

Yowza, you're right (at least for the one case I tried).  This must be a 
new development (where new development is defined as, It wasn't legal in 
the original KR C I learned when I was a pup).

Still, I have seem people do that in code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [1,2,3] exactly same as [1,2,3,] ?

2008-08-30 Thread Roy Smith
In article [EMAIL PROTECTED],
 Fredrik Lundh [EMAIL PROTECTED] wrote:

 Roy Smith wrote:
 
  Yowza, you're right (at least for the one case I tried).  This must be a 
  new development (where new development is defined as, It wasn't legal in 
  the original KR C I learned when I was a pup).
 
 the C 89 grammar appears to be:
 
  initializer:
  assignment-expression
  { initializer-list }
  { initializer-list , }
 
  initializer-list:
  designation-opt initializer
  initializer-list , designation-opt initializer
 
 so a trailing comma has been allowed for around twenty years.
 
 /F

C89 came out about 10 years after I first learned C :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 Peter Otten [EMAIL PROTECTED] wrote:

 Without them it looks better:
 
 import sys
 for line in sys.stdin:
 try:
 a, b = map(int, line.split(None, 2)[:2])
 except ValueError:
 pass
 else:
 if a + b == 42:
 print b

I'm philosophically opposed to one-liners like:

 a, b = map(int, line.split(None, 2)[:2])

because they're difficult to understand at a glance.  You need to visually 
parse it and work your way out from the inside to figure out what's going 
on.  Better to keep it longer and simpler.

Now that I've got my head around it, I realized there's no reason to make 
the split part so complicated.  No reason to limit how many splits get done 
if you're explicitly going to slice the first two.  And since you don't 
need to supply the second argument, the first one can be defaulted as well.  
So, you immediately get down to:

 a, b = map(int, line.split()[:2])

which isn't too bad.  I might take it one step further, however, and do:

 fields = line.split()[:2]
 a, b = map(int, fields)

in fact, I might even get rid of the very generic, but conceptually 
overkill, use of map() and just write:

 a, b = line.split()[:2]
 a = int(a)
 b = int(b)
--
http://mail.python.org/mailman/listinfo/python-list


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 Peter Otten [EMAIL PROTECTED] wrote:

  I might take it one step further, however, and do:
  
  fields = line.split()[:2]
  a, b = map(int, fields)
  
  in fact, I might even get rid of the very generic, but conceptually
  overkill, use of map() and just write:
  
  a, b = line.split()[:2]
  a = int(a)
  b = int(b)
 
 If you go that route your next step is to introduce another try...except,
 one for the unpacking and another for the integer conversion...

Why another try/except?  The potential unpack and conversion errors exist 
in both versions, and the existing try block catches them all.  Splitting 
the one line up into three with some intermediate variables doesn't change 
that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Roy Smith
In article 
[EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 Roy Smith:
  No reason to limit how many splits get done if you're
  explicitly going to slice the first two.
 
 You are probably right for this problem, because most lines are 2
 items long, but in scripts that have to process lines potentially
 composed of many parts, setting a max number of parts speeds up your
 script and reduces memory used, because you have less parts at the
 end.
 
 Bye,
 bearophile

Sounds like premature optimization to me.  Make it work and be easy to 
understand first.  Then worry about how fast it is.

But, along those lines, I've often thought that split() needed a way to not 
just limit the number of splits, but to also throw away the extra stuff.  
Getting the first N fields of a string is something I've done often enough 
that refactoring the slicing operation right into the split() code seems 
worthwhile.  And, it would be even faster :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 Peter Otten [EMAIL PROTECTED] wrote:

 Roy Smith wrote:
 
  In article [EMAIL PROTECTED],
   Peter Otten [EMAIL PROTECTED] wrote:
  
   I might take it one step further, however, and do:
   
   fields = line.split()[:2]
   a, b = map(int, fields)
   
   in fact, I might even get rid of the very generic, but conceptually
   overkill, use of map() and just write:
   
   a, b = line.split()[:2]
   a = int(a)
   b = int(b)
  
  If you go that route your next step is to introduce another try...except,
  one for the unpacking and another for the integer conversion...
  
  Why another try/except?  The potential unpack and conversion errors exist
  in both versions, and the existing try block catches them all.  Splitting
  the one line up into three with some intermediate variables doesn't change
  that.
 
 As I understood it you didn't just split a line of code into three, but
 wanted two processing steps. These logical steps are then somewhat remixed
 by the shared error handling. You lose the information which step failed.
 In the general case you may even mask a bug.
 
 Peter

Well, what I really wanted was two conceptual steps, to make it easier for 
a reader of the code to follow what it's doing.  My standard for code being 
adequately comprehensible is not that the reader *can* figure it out, but 
that the reader doesn't have to exert any effort to figure it out.  Or even 
be aware that there's any figuring-out going on.  He or she just reads it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Advice on long running processes

2007-10-11 Thread Roy Smith
[EMAIL PROTECTED] wrote:

 Hello,
 
 I write a lot of CGI scripts, in Python of course.  Now I need to
 convert some to long-running processes.  I'm having trouble finding
 resources about the best practices to do that.
 
 I've found a lot of email discussions that say something like, You
 need to educate yourself about the differences when you have long-
 running processes but I've not had a lot of luck with finding things
 that explain the differences.

The biggest differences between run-and-exit vs. long running processes are 
resource management and error recovery.  Let's take them one at a time.

Resource management.  In a short-lived process, you really don't have to 
worry about this at all.  Snarf as much memory as you need, open as many 
files as you want, and when you exit, the operating system cleans it all up 
for you.  With a long running process, you have to worry about stuff like 
that.

In Python, you're isolate from the low-level details of memory management, 
but still need to think about it a bit.  Imagine you had code that looked 
like this in your main loop:

for request in getNextRequest():
requestList.append (request)
processRequest(request)

requestList is going to keep growing without bounds and eventually will eat 
up all available memory in the system and your process will crash.  
Everything you store, you also need to delete when you're done with it.

Same with files.  In a short-lived process, you can generally open as many 
files as you want and never worry about closing them.  It unlikely you will 
ever run out of file descriptors.  In a long running process, that's not 
the case.  If you open a new file each time you get a request and never 
close it, after a few hundred requests (depending on the operating system, 
maybe even a few thousand), you'll run out of file descriptors.

The other big thing is error recovery.  In a short lived process, if 
something fails, you print an error message and exit.  In a long running 
process, you need to somehow recover from the error and keep going as best 
you can.  This can be tricky.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can you determine the sign of the polar form of a complex number?

2007-10-17 Thread Roy Smith
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 Just to clarify what I'm after:
 
 If you plot (-3)^n where n is a set of negative real numbers between 0
 and -20 for example, then you get a discontinuos line due to the
 problem mentioned above with fractional exponents. However, you can
 compute what the correct absolute value of the the missing points
 should be (see z2 above for an example), but I would like to know how
 to determine what the correct sign of z2 should be so that it fits the
 graph.

You need to ask this question on a math group.  It's not a Python question 
at all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why did these companies choose Tcl over Python

2007-10-31 Thread Roy Smith
chewie54 [EMAIL PROTECTED] wrote:

 I would prefer to use Python but can't deny how popular Tcl is,  as
 mentioned above,  so my question is why wasn't Python selected by
 these companies as the choice of scripting languages for their
 product?
 
 Are there any obvious advantages like:
 
 performance,
 memory footprint,
 better cross-platform support,
 ease of use,

I used to work on a project which was written mostly in Tcl.  Not a huge 
project, but not a trivial one either.  Perhaps a few 10's of KLOC over 100 
Tcl source files.  The domain was network monitoring using SNMP.  No 
graphics.  We also used a commercially available network simulator (Mimic) 
which was written in Tcl (or, at least, has Mimic as its scripting 
language).

For us, the biggest thing was the quick learning curve (i.e. ease of use).  
Most of the programmers on the team were network jocks, not programmers.  
Getting them up to speed on enough Tcl to do their jobs was very quick.  
Performance was not an issue, since the application was rate limited by the 
network (i.e. waiting for SNMP replies to come back).

We also had lots of hooks into C code.  Doing that is trivial in Tcl.  Yes, 
I know you can extend/embed Python, but it's a LOT easier in Tcl.  
Embedding a Tcl interpreter in a C program is literally one line of code.  
I sat down with the book to figure out how to do it, and had a running 
interpreter going in 10 minutes.  Part of what makes it so easy is that 
everything in Tcl is a string (no need to support multiple data types).

I don't think I would want to write a huge system in Tcl.  For one thing, 
it's not object oriented (I have no direct experience with incr Tcl, so 
that may not be a fair critisism).  It's also slow (even slower than 
Python).  Of course, in both Tcl and Python, the key to a fast application 
is to do all the CPU-intensive parts in C and just script the glue code.

Anyway, I like Tcl.  It's certainly worth considering seriously as a 
scripting language.  As for which is better, Tcl or Python, there's no 
one right answer to that.  Evaluate both and decide which fits your needs 
better.  Often, questions like that will be decided by things which have 
little to do with language technology.  Is your company re-organizing and 
there's a development group who are used to working in language X who are 
looking for a new project?  Guess which language they're going to pick?  
Got a major customer (or prospect) who expresses an interest in language X 
for scripting extensions?  Guess which language you're going to use?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clean way to get one's network IP address?

2007-11-21 Thread Roy Smith
Gilles Ganault [EMAIL PROTECTED] wrote:

 I know about socket.gethostbyname, but this relies on what's in
 /etc/hosts, and I'd rather have a more independent solution.

The system I'm currently working on uses exactly this strategy -- we get 
the hostname then do a name lookup on it.  We've gone around and around on 
this, and ended up with that being the best solution.  For us, anyway.  
Your mileage may vary.

As others have pointed out, it's entirely possible to have multiple IP 
addresses.  In addition, your IP address(es) can change as connections come 
up and down, especially in a mobile environment (WiFi, VPN, cellular, etc).  
There is no single correct answer here.

Oh, BTW, did you mean IPv4 or IPv6?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the annoying, verbose self

2007-11-27 Thread Roy Smith
In article [EMAIL PROTECTED],
 Bruno Desthuilliers [EMAIL PROTECTED] 
 wrote:

 Steven D'Aprano a écrit :
  On Mon, 26 Nov 2007 21:48:36 +0100, Ton van Vliet wrote:
  
  On Mon, 26 Nov 2007 20:14:50 +0100, Bruno Desthuilliers
  [EMAIL PROTECTED] wrote:
 
  However, I was more thinking in terms of attributes only
  Too bad : in Python, everything's an object, so 'methods' are attributes
  too.
  Right, but I'm sure *you* know a way to distinguish between them
 
 Yes : reading the doc. But that's something the compiler will have hard 
 time doing.
 
  (I'm
  just a beginner ;-)
  
  All methods are attributes. Not all attributes are methods. The usual way 
  to see if something is a method is to try calling it and see what 
  happens, but if you want a less informal test, try type():
  
  
  type(''.join)
  type 'builtin_function_or_method'
  type(Foo().foo)  # with the obvious definition of Foo
  type 'instancemethod'
  
 
 
 Fine. Now since Python let you define your own callable types and your 
 own descriptors, you can as well have an attribute that behave just like 
 a method without being an instance of any of the method types - so the 
 above test defeats duck typing. And since you can have callable 
 attributes that are definitively not methods, you can't rely on the fact 
 that an attribute is callable neither.

If you want to have a little fun:

class peverse:
def __call__(self):
raise AttributeError (peverse instance has no __call__ method)

x = peverse()
x()
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Limit Guessing Algorithm

2007-12-02 Thread Roy Smith
In article 
[EMAIL PROTECTED],
 [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 Hello hello,
 
 I'm looking for a piece of code, preferably in Python, that will do
 the following. It will accept a few data points (x,f(x)) of a function
 that converges to some finite value when x converges to infinity. I
 need the algorithm to guess what that limit is, to whatever precision
 it can.
 
 For example, if the input is:
 
 [
 [1,8],
 [2,7.5],
 [3,7.25],
 [4,7.125]
 ]
 
 Then the output will be 7. Or at least something close.
 
 Does anyone know anything like that?

I suggest any introductory calculus or math analysis text.  Perhaps even 
the one your professor assigned you for the course :-)

Look under limits in the table of contents.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python surpasses Perl in TIOBE index

2007-12-04 Thread Roy Smith
In article [EMAIL PROTECTED],
 Daniel Fetchinson [EMAIL PROTECTED] wrote:

 Anyone has an idea what the huge peak around the middle of 2004 can be
 attributed to?

There's a Q/A section at the bottom of 
http://www.tiobe.com/index.htm?tiobe_index which covers this:

Q: What happened to Java in April 2004? Did you change your methodology?
A: No, we did not change our methodology at that time. Google changed its 
methodology. They performed a general sweep action to get rid of all kinds 
of web sites that had been pushed up. As a consequence, there was a huge 
drop for languages such as Java and C++. In order to minimize such 
fluctuations in the future, we added two more search engines (MSN and 
Yahoo) a few months after this incident.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distinguishing attributes and methods

2007-12-08 Thread Roy Smith
In article [EMAIL PROTECTED],
 Bruno Desthuilliers [EMAIL PROTECTED] wrote:

 MonkeeSage a écrit :
  On Dec 8, 2:51 pm, Glenn Hutchings [EMAIL PROTECTED] wrote:
  
 On Dec 8, 7:44 pm, MonkeeSage [EMAIL PROTECTED] wrote:
 
 
 I think it muddies the water to say that a.a() and a.a are the same
 thing--obviously they are not.
 
 A thing is not what it is;
 A thing is what it does.
 This is the Way of the Duck.
 
 -- Basho (in his 3 extra syllables phase)
  
  
  Bah. Type-by-behavior never impressed me much. And I still think that
  a.a is semantically different from a.a() in python.
 
 It is indeed and very obviously semantically different, and no one said 
 it wasn't. The first is an attribute lookup, the second is an attribute 
 lookup followed by a call. Now this doesn't make the attribute lookup 
 part different in both cases...

There are a very few corner cases were you can leave the ()'s out.  For 
example, you can do;

raise Exception

or

raise Exception()

but stuff like that is very much a wart in the language syntax.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PEP 354: Enumerations in Python

2006-02-28 Thread Roy Smith
Ben Finney [EMAIL PROTECTED] wrote:

  a = enum ('foo', 'bar', 'baz')
  b = enum ('foo', 'bar', 'baz')
 
 Two separate enumerations are created

OK, most of the rest follows from that.

  str (a)
 
 Not defined in the current specification. Suggestions?

Well, by analogy with

 a = set ((1, 2, 3))
 print '%s' % a
set([1, 2, 3])

I would think:

enum('foo', 'bar', 'baz')

would make sense.

  repr (a)
 
 Not defined in the current specification. Suggestions?

Hmm.  Maybe what I suggested for str() would work for repr() too.  I'm a 
little worried, however, about things that aren't == but print the same.  
It might make more sense for repr() to include the id (in the style of 
'__main__.x instance at 0x8208f6c').  Same with the repr() of an enum 
member.

  hash (a)
 
 -1210774164  # or some other hash value

I saw some debate about mutable or immutable.  Doesn't making something 
hashable kinda-sorta mean it has to be immutable?

  You imply that it works from An enumerated type is created from a
  sequence of arguments to the type's constructor, but I suspect
  that's not what you intended.
 
 That's what I intended; a sequence of arguments. Is there a better way
 to refer to the positional arguments collectively?

I'm not really a language lawyer, so I can't say.  I was mostly trying to 
explore the corners of the envelope.

  There's been a number of threads recently where people called 
  regex methods with flags (i.e. re.I) when integers were expected, with 
  bizarre results.  Making the flags into an enum would solve the problem 
  while retaining backwards compatibility.
 
 Yes, this is a prime use case for enums. I tried to cover this in the
 Motivation::
 
 Other examples include error status values and states
 within a defined process.
 
 Can anyone think of a better way to express this, without necessarily
 referring to any specific set of flags or states or codes or whatever?

Cite the regex thread :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use empty string for self

2006-02-28 Thread Roy Smith
[EMAIL PROTECTED] wrote:
 Any comments?  Has this been discussed before?

Yes.  To death.  Executive summary: self is here to stay.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use empty string for self

2006-02-28 Thread Roy Smith
Terry Hancock [EMAIL PROTECTED] wrote:
 However, there is a slightly less onerous method which
 is perfectly legit in present Python -- just use s
 for self:

This is being different for the sake of being different.  Everybody *knows* 
what self means.  If you write your code with s instead of self, it just 
makes it that much harder for other people to understand it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-03-01 Thread Roy Smith
In article [EMAIL PROTECTED],
 greg [EMAIL PROTECTED] wrote:

 Paul Rubin wrote:
 
  Do you anticipate having parameters like socket.AF_INET that are
  currently integers, become enumeration members in future releases?
 
 Since these are derived from values defined
 as integers in C, it's probably better to leave
 them that way. There may be code that relies
 on them being integers or having those integer
 values.

On a thin API like python's socket module, adding anything which isn't 
there in the lower level is a mistake (and making AF_INET an enum member 
would be adding something which isn't there).

I just finished adding IPv6 support to a product that didn't have it 
before.  We've got a platform independent socket interface which treats 
the address family as opaque data.  It turns out, I had to make ZERO 
changes to this shim layer.  Had the layer known more about address 
families, I would have had a lot more work to do.

Consider, for example, Python running on a system with experimental 
AF_INET8 support at some point in the future.  As it stands now, the Python 
library code doesn't need to know there's a new address family if all you 
want to do is open raw AF_INET8 sockets.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-03-01 Thread Roy Smith
Tim Chase  [EMAIL PROTECTED] wrote:
 Do you anticipate having parameters like socket.AF_INET
 that are currently integers, become enumeration members
 in future releases?
 
 Since these are derived from values defined as integers
 in C, it's probably better to leave them that way. There
 may be code that relies on them being integers or having
 those integer values.

I'd say that because something is done in C, it's the best 
way to do it in Python is a bad line of reasoning :)  If I 
wanted C, I'd use C.

The problem is that the C language binding in this case is simply
exposing the even lower level operating system interface.  At that
level, the address family is indeed just an arbitrary integer.

The socket man page on (for example) Solaris-9 says things like, The
currently understood formats are, and If a protocol is specified by
the caller, then it will be packaged into a socket level option
request and sent to the underlying pro- tocol layers.  You don't
really know for sure if you used a valid value until the low-level
protocol drivers look at the number you passed in.  This doesn't sound
like an enum to me.

There are plenty of places where we pass around integers that would be
better served by enums.  Address families and protocol numbers in the
socket interface just isn't one of them.

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


Re: Use empty string for self

2006-03-01 Thread Roy Smith
John Salerno  [EMAIL PROTECTED] wrote:
I do get it. I think I will just have to get used to seeing the 'self' 
argument but understanding that it's not really something that is always 
passed in. I'm trying to train myself to see

def doittoit(self) as def doittoit()

That's OK as far as using your C++ experience to help understand
Python by analogy, but don't fall into the trap of trying to write C++
in Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-03-01 Thread Roy Smith
 Should I amend the PEP to propose either in the builtins
 or in the collections module? Or should I propose two
 PEPs and let them compete?

I see the issue of whether it's a built-in or part of the standard library 
as being a detail.  My personal opinion is that they're important enough to 
be built in, but having to write import enum (or whatever) won't kill me.  
If making it a builtin becomes a point of contention, drop it and 
concentrate on the more key issues of how enums will behave.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-02 Thread Roy Smith
In article [EMAIL PROTECTED],
 John Salerno [EMAIL PROTECTED] wrote:

 Since Python does so many things different, especially compared to 
 compiled and statically typed languages, do most of the basic design 
 patterns still apply when writing Python code? If I were to read a 
 design pattern book (such as Head First Design Patterns), could I apply 
 their Java examples to Python easily enough, or does Python require a 
 different perspective when applying patterns?

Many of the classic design patterns apply just fine to Python, at least in 
the high-level view.  On the other hand, much (most?) of what's in the 
classic design pattern books is so tied up with ways around C++/Java type 
bondage, it's difficult to see the forest for the trees.

For example, take the most classic of all patterns, Singleton.  A typical 
C++ Singleton treatment will be all about making constructors private and 
shit like that.  None of that carries over to Python.  What I would do in 
Python is have a module-level factory function which caches a single 
instance of the class to return to the 2nd and subsequent caller and not 
get my panties in a twist over the fact that some clever programmer could 
find away around my code and force creation of a second instance.

The basic concepts in the pattern books are worth knowing.  You just have 
to be able to tease apart the concepts from the language-specific cruft 
that so often obfuscates the descriptions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-02 Thread Roy Smith
In article [EMAIL PROTECTED],
 Paul Rubin http://[EMAIL PROTECTED] wrote:

 Somewhat less often, something is easy in Java and difficult in
 Python.

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


Re: do design patterns still apply with Python?

2006-03-02 Thread Roy Smith
In article [EMAIL PROTECTED],
 Paul Rubin http://[EMAIL PROTECTED] wrote:

 Roy Smith [EMAIL PROTECTED] writes:
   Somewhat less often, something is easy in Java and difficult in
   Python.
  Example?
 
 Sandboxed code is a real obvious one.

What is sandboxed code?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question

2006-03-02 Thread Roy Smith
In article [EMAIL PROTECTED],
 Tom Leggio [EMAIL PROTECTED] wrote:

 Do I need this on my computer---Python---can I remove it without hurting 
 anything?
 Thanks Tommy

Tom,

That's a very difficult question to answer without knowing more about your 
computer.  Some systems depend on Python for administrative tasks.  If you 
remove Python on such a system, you could create a mess for yourself.

Why do you want to remove it?  Even if you never use it, it's probably not 
taking up much space and it's not hurting anything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 msoulier [EMAIL PROTECTED] wrote:

 For example, the Factory pattern is mostly to work around the fact that
 it's difficult in Java and C++ to dynamically load classes.

You're over-specifying.  Most of most design patterns is to work around the 
fact that it's difficult in Java and C++ to do many things.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 Ben Caradoc-Davies [EMAIL PROTECTED] wrote:

 James Stroud wrote:
  except URLError, HTTPException:
 
 Aieee! This catches only URLError and binds the name HTTPException to 
 the detail of that error. You must write
 
 except (URLError, HTTPException):
 
 to catch both.

This exact issue came up just within the past week or so.  I think that 
qualifies it as a wart, but I think it's a double wart.

It's certainly a wart that the try statement syntax allows for such 
ambiguity.  But, I think it's also a wart in how the exceptions were 
defined.  I like to create a top-level exception class to encompass all the 
possible errors in a given module, then subclass that.  This way, if you 
want to catch anything to goes wrong in a call, you can catch the top-level 
exception class without having to enumerate them all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Roy Smith
Rene Pijlman [EMAIL PROTECTED] wrote:

 A catchall seems like a bad idea, since it also catches AttributeErrors
 and other bugs in the program.

All of the things like AttributeError are subclasses of StandardError.  You 
can catch those first, and then catch everything else.  In theory, all 
exceptions which represent problems with the external environment (rather 
than programming mistakes) should derive from Exception, but not from 
StandardError.  In practice, some very old code may raise things which do 
not derive from Exception, which complicates things somewhat.

--
#!/usr/bin/env python   


import socket

try:
x = []
y = x[42]
except StandardError, foo:
print Caught a StandardError: , foo
except Exception, foo:
print Caught something else: , foo

try:
socket.socket ()
except StandardError, foo:
print Caught a StandardError: , foo
except Exception, foo:
print Caught something else: , foo

try:
raise I'm a string pretending to be an exception
except StandardError, foo:
print Caught a StandardError: , foo
except Exception, foo:
print Caught something else: , foo
--

Roy-Smiths-Computer:play$ ./ex.py
Caught a StandardError:  list index out of range
Caught something else:  (43, 'Protocol not supported')
Traceback (most recent call last):
  File ./ex.py, line 21, in ?
raise I'm a string pretending to be an exception
I'm a string pretending to be an exception
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to except the unexpected?

2006-03-04 Thread Roy Smith
In article [EMAIL PROTECTED],
 Rene Pijlman [EMAIL PROTECTED] wrote:

 Roy Smith:
 In theory, all exceptions which represent problems with the external 
 environment (rather than programming mistakes) should derive from 
 Exception, but not from StandardError.
 
 Are you sure?
 
 
 The class hierarchy for built-in exceptions is:
 
 Exception
  +-- StandardError
  |+-- KeyboardInterrupt
  |+-- ImportError
  |+-- EnvironmentError
  ||+-- IOError
 
 http://www.python.org/doc/current/lib/module-exceptions.html

Hmmm, OK, I missed EnvironmentError.  So, what you need to do is:

try:
   whatever()
except EnvironmentError:
   ...
except StandardError:
   ...
except Exception:
   ...

or something like that.

I do agree with you that there is some value in Java's must catch or 
re-export all exceptions semantics, and this would be one of those places 
where it would be useful.  In general, however, I've always found it to be 
a major pain in the butt, to the point where I sometimes just punt and 
declare all my methods to throw Exception (or whatever the correct syntax 
is).  Not to mention that with a dynamic language like Python, it's 
probably impossible to implement.

I think the real problem here is that the on-line docs are incomplete 
because they don't list all the exceptions that this module can raise.  The 
solution to that is to open a bug on sourceforge against the docs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why I chose Python over Ruby

2006-03-05 Thread Roy Smith
Xavier Morel [EMAIL PROTECTED] wrote:

 Francois wrote:
  1) In Ruby there is a risk of Variable/Method Ambiguity when calling
  a method with no parameters without using () :
  
 Yes, but that's in my opinion a programmer error, not necessarily a 
 language error.

In Python, you can make exactly the opposite error.  Both of these are 
perfectly legal and reasonable things to write, where foo is a function:

   a = foo
   a = foo()

Actually, if you want to have a little fun, try:

   def foo:
  return foo

then you can write:

   a = foo
   a = foo()
   a = foo()()
   a = foo()()()
   a = foo()()()()
   etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why I chose Python over Ruby

2006-03-06 Thread Roy Smith
In article [EMAIL PROTECTED],
 Bil Kleb [EMAIL PROTECTED] wrote:

 The parensless calls also allow one to write beautiful
 DSLs with Ruby.

What's a DSL?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: processing the genetic code with python?

2006-03-06 Thread Roy Smith
In article [EMAIL PROTECTED],
nuttydevil [EMAIL PROTECTED] wrote:
I have many notepad documents that all contain long chunks of genetic
code. They look something like this:

atggctaaactgaccaagcgcatgcgtgttatccgcgagaaagttgatgcaaccaaacag
tacgacatcaacgaagctatcgcactgctgaaagagctggcgactgctaaattcgtagaa
agcgtggacgtagctgttaacctcggcatcgacgctcgtaaatctgaccagaacgtacgt
ggtgcaactgtactgccgcacggtactggccgttccgttcgcgtagccgtatttacccaa

Basically, I want to design a program using python that can open and
read these documents.

Start by googling for biopython.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking function calls

2006-03-07 Thread Roy Smith
Fredrik Tolf  python-list@python.org wrote:
If I have a variable which points to a function, can I check if certain
argument list matches what the function wants before or when calling it?

Currently, I'm trying to catch a TypeError when calling the function
(since that is what is raised when trying to call it with an illegal
list), but that has the rather undesirable side effect of also catching
any TypeErrors raised inside the function. Is there a way to avoid that?

The only way is to read the documentation for the function (or, the
source code).

Can you be a little more specific about what you're trying to do?  Can
you post your code?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning different languages

2006-03-07 Thread Roy Smith
Rich [EMAIL PROTECTED] wrote:
 Anyway, my question is: what experience you people have with working
 with different languages at the same time?

At one point, I was working with Perl, Python, Tcl, and C++ all more or 
less at the same time.  I just kept crib sheets handy, so I could look up 
syntax whenever I needed to.  Which was about every time I needed to write 
a for loop and didn't have an example handy in the same piece of code to 
remind me what I was supposed to type.

 I'm more thinking about Python, PHP, C++, Perl, Euphoria, which are
 languages I'm thinking of learning now.

This seems like a reasonable set (I've never heard of Euphoria; I'll need 
to do some google/wikipedia work tonight on that one :-)).  If you're 
trying to build a good resume, I'd probably add Java and/or C# to the mix.  
Of course, with a list that long, we're probably talking a year or two of 
study, unless you plan on doing the most cursory job on each.

 How is your experience with handling these paralell?. And what would
 you recommend - take one (or perhaps two) at a time, and then continue
 with the next? Or is it OK to go ahead with them all, at once?

I try to learn a new language per year.  Sometimes it's just a quick glance 
(I spent about a day playing with Forth last year), other times it's a 
deeper look with a serious project or two (those are generally ones with 
resume appeal, but not always).  In any case, I think one at a time makes 
the most sense.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type Hinting vs Type Checking and Preconditions

2006-03-07 Thread Roy Smith
In article [EMAIL PROTECTED],
 Tom Bradford [EMAIL PROTECTED] wrote:

 Here is what I mean.  The following function, though conventionally
 indicating that it will perform a multiplication, will yield standard
 Python behaviors if a string value is passed to it:
 
 def multiplyByTwo(value):
 return value * 2
 
 Passing 14 to it will return 28, whereas passing 14 to it will return
 1414.  Granted, we know and accept that this is Python's behavior
 when you multiply two values, but because we don't (and shouldn't have
 to) know the inner workings of a function, we don't know that the types
 of the values that we pass into it may adversly affect that results
 that it yields.

The question is, what is the function *supposed to do*?  Without knowing 
what it is *supposed to do*, it is impossible to say for sure whether 
returning 1414 is correct or not.  Consider two different functions:

def multiplyByTwo_v1(value):
Returns the argument multiplied by 2.  If the argument is a
   string representation of an integer, another string is returned
   which is the string representation of that integer multiplied
   by 2.

return value * 2

def multiplyByTwo_v2(value):
Returns the argument multiplied by 2.

return value * 2

The first one should return 28 when passed 14.  If it returns 1414, 
it's broken.  I know this seems rather silly and pedantic, but it's an 
important point.

I was once working on a project which historically didn't have any unit 
tests.  We had a function called something like isValidIP in the library 
which returned True or False depending on whether its (string) argument was 
a valid IP address.

I wrote some unit tests and it failed on a corner case like 
255.255.255.255 (or maybe it was 0.0.0.0).  Turns out, the original 
author was using it in some special situation where 255.255.255.255 wasn't 
valid for his purposes.  We got down to, OK, *you* document what the 
function is supposed to do, and *I'll* write a unit test which proves it 
does what the documentation says.  You would think that would be easy, but 
it never got done because we couldn't get everybody to agree on what the 
function was supposed to do.

It was being used in production code.  I would have thought it would bother 
people that we were using a function without knowing what it was supposed 
to do, but what really bothered people more was that we had a unit test 
that was failing.  And the solution was to back out unit test.  Sometimes 
politics trumps technology.

PS, as far as I know, that project is now dead, but for other reasons far 
worse than one underspecified function :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New python.org website

2006-03-08 Thread Roy Smith
The first two links on the News and Announcements are dead -- they get 
you a 404 File Not Found.  I've opened a critical ticket on this in the 
bug tracker.  I see there's another ticket open already on a similar issue.

My recommendation would be that if these can't be resolved in very short 
order. to revert to the old site until these are fixed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why no block comments in Python?

2006-03-08 Thread Roy Smith
Fredrik Lundh [EMAIL PROTECTED] wrote:
 you can quickly comment out regions by putting them
 inside a triple-quoted string.)

Except that triple-quotes don't nest.

I do agree, however, with the idea that any decent editor should be
able to comment out a block of code faster than I can type this
sentence.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why no block comments in Python?

2006-03-08 Thread Roy Smith
Warby [EMAIL PROTECTED] wrote:
Eliminating block comments eliminates uncertainty.  :)

An even better way to eliminate uncertainty is to eliminate the code.
Commenting out is fine for a quick test during development.  Once the
code is committed, the dead code should be eliminated completely.

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


Re: is there any overheard with try/except statements?

2006-03-08 Thread Roy Smith
In article [EMAIL PROTECTED],
 John Salerno [EMAIL PROTECTED] wrote:

 One of the things I learned with C# is that it's always better to handle 
 any errors that might occur within the codes itself (i.e. using if 
 statements, etc. to catch potential out of range indexing) rather than 
 use too many try/catch statements, because there is some overhead every 
 time the program encounters the try.
 
 Is this the case at all with Python, in terms of extra work or slower 
 speed? Or is try/except implemented differently in Python than it is in 
 other languages, so that it runs just like any other code?
 
 Thanks.

Repeat after me: Python is not fill in name of your favorite language

In C++ (and, I assume, C#), exception handling is relatively expensive, and 
is avoided for this reason.  It's also avoided (in C++, anyway) because 
it's only in the past few (5-10) years that you could pretty much count on 
whatever compiler you were using implementing them correctly.  Lastly, many 
C++/C# programmers came from C, where exceptions don't exist, so they're 
not used to using them.

But, that's not Python.  In Python, exceptions work as advertised, and 
they're cheap.  The pythonic way to do things is to embrace the maxim that 
it's easier to ask forgivness than to ask permission.  It is usually 
cleaner and faster to write a try block than an if statement.  For example, 
I'll write:

try:
   x = foo[y]
except IndexError:
   blah

instead of

if y  len (foo):
   x = foo[y]
else:
   blah

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


Re: why no block comments in Python?

2006-03-09 Thread Roy Smith
msoulier [EMAIL PROTECTED] wrote:
 (and if you don't, you can quickly comment out regions by putting them
 inside a triple-quoted string.)

Although that will use up memory, as opposed to a comment.

I can't imagine a realistic scenario where the amount of memory wasted
by triple-quoting out code could possibly be significant.

I'll also repeat what I said before -- good software engineering
practice demands that you remove dead code completely.  Commenting
something out for a quick test during development is OK, but once it
reaches the production stage, get rid of it.  It'll still live in your
revision control system.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New python.org website

2006-03-09 Thread Roy Smith
msoulier [EMAIL PROTECTED] wrote:
I don't mind the logo or the colour scheme, but I do mind the first
paragraph in bolded text. What, you figure the readers can't figure out
how to find What is Python? by themselves?

Bold should be used sparingly. This is serious overuse.

I'm OK with bold for stuff like this, but the wording could be better.  The
last sentence:

Many Python programmers report substantial productivity
gains and feel the language encourages the development of
higher quality, more maintainable code.

reads like a drug warning label, carefully crafted to not run afoul of
regulatory constraints.  Just say what you want to say:

Python programmers are more productive and the language
encourages development of higher quality, more maintainable
code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to have a for-loop index?

2006-03-09 Thread Roy Smith
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 I write a lot of code that looks like this:
 
 for myElement, elementIndex in zip( elementList,
 range(len(elementList))):
 print myElement , myElement,  at index: ,elementIndex
 
 
 My question is, is there a better, cleaner, or easier way to get at the
 element in a list AND the index of a loop than this?
 
 TIA,
 Andrew

The real question is *why* do you want the index?

If you're trying to iterate through list indicies, you're probably trying 
to write C, C++, Fortran, Java, etc in Python.

Can you describe exactly what it is that you're trying to do?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Roy Smith
Dmitry Anikin [EMAIL PROTECTED] wrote:
 There are often situations when a function has independent
 parameters, all having reasonable defaults, and I want to
 provide just several of them. In fact, I can do it using
 keyword parameters, but it's rather long and you have to
 remember/lookup names of parameters.

Specifying the names of the keyword parameters costs you a little typing 
once, but saves everybody (including yourself) a lot of grief later when 
you're trying to figure out what the heck your code does 6 months later.

 I badly need this feature in embedded python app (for
 compatibility with other language that uses such syntax)

Can you tell us more about what it is that you're trying to do?

 Or maybe it might be an idea for enhancement proposal?

You can always write up a PEP, but to be honest, this doesn't sound like 
one that would meet with much enthusiasm from the community.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Roy Smith
In article [EMAIL PROTECTED],
 Antoon Pardon [EMAIL PROTECTED] wrote:

 Op 2006-03-10, Roy Smith schreef [EMAIL PROTECTED]:
  Dmitry Anikin [EMAIL PROTECTED] wrote:
  There are often situations when a function has independent
  parameters, all having reasonable defaults, and I want to
  provide just several of them. In fact, I can do it using
  keyword parameters, but it's rather long and you have to
  remember/lookup names of parameters.
 
  Specifying the names of the keyword parameters costs you a little typing 
  once, but saves everybody (including yourself) a lot of grief later when 
  you're trying to figure out what the heck your code does 6 months later.
 
 Could you explain what is so hard in figuring out:
 
   func(,,4)

Because while I probably remember what func does (especially if it's well 
named), it's less likely that I remember all the arguments it takes, and 
even less that I remember what order they come in.

Let's say I've got a function which makes a network connection.  It takes 
optional arguments for a port number to connect to, a timeout (in seconds) 
and a buffer size (in kbytes) to use.  If we used your syntax, what does 
connect (,,20) mean?  You have to go look up the definition of the 
function to find out, don't you?  But, if I wrote connect (port=20), it's 
obvious to anybody reading the code what the 20 is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Roy Smith
Antoon Pardon  [EMAIL PROTECTED] wrote:
Do you have trouble remembering that range(n) is actually providing the
second parameter to the function and what it does?

Yes.  I don't use range() everyday, and it's very rare that I use more
than one argument.  I do remember that there are additional (optional)
arguments to range which alter the sequence (start point and step),
but I certainly don't remember which is which.  If I needed to use it,
I would go look it up.  On the other hand, if I saw range (10,
step=2) written, it would be immediately obvious what was going on
without need to refer to the docs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why no block comments in Python?

2006-03-11 Thread Roy Smith
In article [EMAIL PROTECTED],
 Jonathan Gardner [EMAIL PROTECTED] wrote:

 Warby wrote:
  ...and I forgot to mention that the output of grep and diff is far more
  understandable in the absence of block comments!
 
 Which is why people do this /anyway/. (Kind of makes block comments
 pointless, doesn't it?
 
 /* This is a 
  * really
  * really
  * long
  * block comment */

Habit left over from the C days.  It was the only way of making a block 
comment stand out visually.  C++ has // comments, just like Python has #, 
but old habits die hard.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: global, globals(), _global ?

2006-03-15 Thread Roy Smith
In article [EMAIL PROTECTED],
 robert [EMAIL PROTECTED] wrote:

 Using global variables in Python often raises chaos. Other languages use 
 a clear prefix for globals.

Unsing globals raises chaos in any language.  They should be shunned and 
avoided.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Have you ever considered of mousing ambidextrously?

2006-03-18 Thread Roy Smith
WangQiang [EMAIL PROTECTED] wrote:
 I'm also a programmer, as working in front of computer day and day, my
 right hand is so tired and ached. So I tried to mouse in both hands. I
 find that it is really an efficient way to release pains. At first I
 switched the mouse buttons in windows control panel, but it taked me
 several steps to finish it

I never understood why people switch mouse buttons.  I'm left handed, so I 
put the mouse on the left side of my keyboard.  It never occurred to me to 
flip the buttons around.

When somebody right handed sits down at my keyboard, I often see them 
trying to avoid using the mouse (using arrow keys, control keys, anything 
to avoid mousing).  I just pick up the mouse and move it over to the right 
side for them, and then they often say, But, the buttons are backwards 
now.  Apparently most right handers *expect* that I, as a sinister mouse 
user, have changed the buttons.  Why?

Of course, I grew up (and still prefer) the Mac, where there *is* only one 
button.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ipv6 validation

2006-03-18 Thread Roy Smith
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 Hello,
 is there any common function for validation if string contains valid ip
 address(both ipv4 and ipv6)? Or does sb wrote some regular expression
 for this?
 thanks
 J

Look at socket.inet_pton().  First check to make sure ipv6 is supported on 
your platform, then pass your string to inet_pton() inside of a try block 
to catch socket.error.  It would have been nicer is a more specific 
exception was thrown, but this seems to work.  For example:

 socket.has_ipv6  
True
 socket.inet_pton(socket.AF_INET6, 8001::1244)
'\x80\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x12D'
 socket.inet_pton(socket.AF_INET6, 8001:xyz:1244)
Traceback (most recent call last):
  File stdin, line 1, in ?
socket.error: illegal IP address string passed to inet_pton
 

Be aware that IPv6 support is messy on Windows.  For example, if you're 
running Win 2003 (or XP, I would guess), the OS does support IPv6 (and thus 
socket.has_ipv6 will probably bet set to True) but the IPv6 libraries don't 
actually get loaded until you configure an IPv6 address on some interface.  
This means things like inet_pton() will fail, which is truly bletcherous 
and evil.

Writing a regex to recognize valid IPv6 presentation strings is not 
trivial.  Keep in mind that you're allowed exactly 0 or 1 :: occurrances, 
and things like ::192.168.11.1 are legal (I don't remember if I got 
the semantics right there, but the syntax is legal).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Have you ever considered of mousing ambidextrously?

2006-03-18 Thread Roy Smith
In article [EMAIL PROTECTED],
 Scott David Daniels [EMAIL PROTECTED] wrote:

 Roy Smith wrote:
  I never understood why people switch mouse buttons.  I'm left handed, so I 
  put the mouse on the left side of my keyboard.  It never occurred to me to 
  flip the buttons around.
 Well, I switch 'em because the forefinger is primary is ingrained.

I do both buttons with my forefinger.  It just seems like the normal thing 
to do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where can we find top-notch python developers?

2006-03-18 Thread Roy Smith
In article [EMAIL PROTECTED],
 Nicholas Reville [EMAIL PROTECTED] wrote:

 Hi, I hope this is an OK spot for this question:

An even better place would be to post your position on the Python Jobs 
Board, http://www.python.org/community/jobs/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where can we find top-notch python developers?

2006-03-18 Thread Roy Smith
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] (Alex Martelli) wrote:

 Unfortunately, I entirely understand _why_ most software development
 firms prefer face-to-face employees: when I found myself, back when I
 was a freelance consultant, alternatively working remotely for some
 time, and at the client's office for another part of the time, I saw my
 productivity soar by 3-4 times when I was working locally, physically
 right next to the rest of the team, rather than remotely 

Actually, it's a quadratic problem.  If your productivity goes up N-fold by 
having face time with your co-workers, consider also that your co-workers' 
productivity also goes up N-fold by having face time with you.

For the most part I find coding to be a solitary activity (unless I'm doing 
pair programming, but that's another post).  Face time is good for design, 
code review, and solving problems.  It's also good for catching snippets of 
conversations which aren't directly related to what you're doing but keep 
you in the big-picture loop anyway.  Most of the really good design work 
I've been involved in has happened during random spontaneous hallway 
discussions.  You start with, Hey, Joe, what do you think about ...?, 
then you go find an empty room with a whiteboard, and a couple of hours 
later, you've both earned your salaries for the month.  Sometimes, somebody 
who you didn't even think knew anything about the topic of discussion will 
notice what you're drawing on the board and contribute what turns out to be 
the winning idea.  That's really hard to do when working remotely (even if 
you're both in the same time zone, let alone 5, or 8, or 12 hours apart).

I find my most productive way of working is to come into the office every 
day and appear to get nothing useful done.  I go to meetings, schmooze, 
argue, eat lunch with co-workers, try to sell my ideas to anybody who I can 
get to listen, and deal with bureaucratic stupidity.  Then I got home and 
get in a good 3 or 4 solid hours of coding where there's nobody to bother 
me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Have you ever considered of mousing ambidextrously?

2006-03-19 Thread Roy Smith
In article [EMAIL PROTECTED],
 John Salerno [EMAIL PROTECTED] wrote:

 Roy Smith wrote:
  In article [EMAIL PROTECTED],
   Scott David Daniels [EMAIL PROTECTED] wrote:
  
  Roy Smith wrote:
  I never understood why people switch mouse buttons.  I'm left handed, so 
  I 
  put the mouse on the left side of my keyboard.  It never occurred to me 
  to 
  flip the buttons around.
  Well, I switch 'em because the forefinger is primary is ingrained.
  
  I do both buttons with my forefinger.  It just seems like the normal thing 
  to do.
 
 How do you manage that? Do you keep your finger hovered over the mouse? 
 It seems like quite an effort to move it back and forth between the two 
 buttons, unless you have a smaller mouse.

Mostly, I've got both hands on the keyboard.  I don't spend a lot of time 
holding the mouse.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what's the general way of separating classes?

2006-03-20 Thread Roy Smith
John Salerno  [EMAIL PROTECTED] wrote:
 From my brief experience with C#, I learned that it was pretty standard 
practice to put each class in a separate file. I assume this is a 
benefit of a compiled language that the files can then be grouped together.

What I'm wondering is how is this normally handled in Python? Is it 
normal for classes to be put in separate modules? It seems like this can 
get out of hand, since modules are separate from one another and not 
compiled together. You'd end up with a lot of import statements.

Are related classes put into a single module then? Or is there some 
recommended method for how to handle this?

There are two different issues here.  One is how you organize your
source code, the other is what API you expose to the user.

From the source code point of view, I will generally put a single
class in each file, but there are exceptions (no pun intended).  If
I've got a bunch of very closely related classes, especially if
they're small, I'll put more than one class in a file.  How small is
small?  There's no hard number, but anything that's got more than a
couple of methods is probably not small.  Exception classes certainly
don't get their own file; they get put in the module where they make
the most sense.

From the API point of view, just because you split your classes up
into multiple modules, doesn't mean the user has to see that
complexity.  Have one top level module which imports the others.  The
user only has to import the top level one.

There's no magic answer here.

To give you a real example, I just took a look at a recent project I
did.  I've got 8 python source files, totalling 1505 lines.  I define
14 classes, of which 7 are exception classes.  My top level module
(the one a user would import) has no classes defined in it; it imports
the other modules and has a bunch of factory functions.  I looked at
the one file that contains two real classes; one of them is
essentially an inner class and has only two methods; __init__() and
__call__(), both of which are trivial.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Remote teamwork anecdotes

2006-03-20 Thread Roy Smith
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] (Alex Martelli) wrote:

 And even if I'm wrong, and a Joe Supercoder I've never met
 works best with 3 days a week of solo effort, 3 days of solo coding plus
 2 of strong in-person interaction is NOT the same thing as, say, 3
 _weeks_ of solo coding plus 2 of close in-person presence.

It's not hard to imagine somebody locking themselves in a cave, coding like 
mad for a week, and producing reams of working code.  What *is* hard to 
imagine is that somewhere along the line they didn't get off on some 
bizarre design tangent and what they produced is reams of code that works, 
but does the wrong thing, or in the wrong way, or just plain isn't what we 
needed.

I think the real advantage to pair programming is that it gives you lots of 
small course corrections, before you're emotionally invested in The Wrong 
Thing.  We sit down together, I come up with a brilliant idea, and you 
shoot it down.  We argue about it for a while, and 10 minutes later I 
(hopefully) see the error of my ways and we set off again in the right 
direction.  Contrast that with me showing up with a week's worth of code 
and you pointing out a fundamental design flaw I made four and a half days 
ago.  By this point, I've got so much invested in the code, I'm more likely 
to just dig my heels in.  It's just too painful to admit at this point that 
everything I did last week is garbage.

Pair programming is not easy.  One of the hard things is to learn to let 
go.  I can't tell you how many times I've been sure I'm right, but decided 
to let my partner have his way because otherwise we'd make no progress, 
only to have him volunteer 15 minutes later, Hmmm, maybe you were right 
after all.  Actually, I can tell you.  It's about the same amount of times 
it's happened in the other direction.  Sometimes the best way to win an 
argument is to take a dive and give the other guy enough rope to hang 
himself with :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between 'is' and '=='

2006-03-27 Thread Roy Smith
In article [EMAIL PROTECTED],
 Joel Hedlund [EMAIL PROTECTED] wrote:

 Which means that is comparisons in general will be faster than == 
 comparisons.

I thought that == automatically compared identify before trying to compare 
the values.  Or am I thinking of some special case, like strings?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doctest, unittest, or if __name__='__main__'

2006-03-28 Thread Roy Smith
In article [EMAIL PROTECTED],
 Paul Rubin http://[EMAIL PROTECTED] wrote:

 [EMAIL PROTECTED] [EMAIL PROTECTED] writes:
   I have noticed some distinctly funny and confused feelings I get when
  using the unittest module, stuff that feels clunky and odd about how it
  is set-up, however I thought that this was just  due to *my personal*
  lack of understanding of the deep magic and sophisticated design
  patterns used in this module!
  
  If it turns out to be 'unpythonic' 
 
 The unpythonicness stems from it being basically a reimplementation of
 JUnit, which was designed for use with Java.

JUnit, in turn, is based on a package first implemented in SmallTalk 
(http://www.xprogramming.com/testfram.htm).

On stuff like this, I'm not opposed to things being slightly unpythonic.  
PyUnit does have some clunkyness to it, but there is some value in having 
all the unit test frameworks have a similar feel across languages.  
Unfortunately, it has become fashionable to call any sort of unit test 
framework xxxUnit, whether or not it resembles the original or not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 licensing: stop this change

2006-04-01 Thread Roy Smith
In article [EMAIL PROTECTED],
 Steve Holden [EMAIL PROTECTED] wrote:

 As the only director of the Python Software Foundation to vote against a 
 recent Board motion to implement the change in licensing terms described in
 
http://pyfound.blogspot.com/2006/04/python-25-licensing-change.html
 
 I would like to place on record my protest against this change. I think 
 it will harm the Python language and ultimately be counter-productive, 
 reducing the user base and discouraging open source programmers from 
 contributing to the code base.
 
 If you disagree with this proposed change it's not too late to do 
 something about it. If this change goes ahead it will be the end of 
 Python as we know it.
 
 regards
   Steve

Absolutely agree.  This is a disaster.  Specifying the use of $US will shut 
out our friends who use quatloos or gold pressed latinum for currency.  Bad 
idea.
-- 
http://mail.python.org/mailman/listinfo/python-list


Scatter/gather on sockets?

2006-04-01 Thread Roy Smith
I've got a bunch of strings in a list:

vector = []
vector.append (foo)
vector.append (bar)
vector.append (baz)

I want to send all of them out a socket in a single send() call, so
they end up in a single packet (assuming the MTU is large enough).  I
can do:

mySocket.send (.join (vector))

but that involves creating an intermediate string.  Is there a more
efficient way, that doesn't involve that extra data copy?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scatter/gather on sockets?

2006-04-01 Thread Roy Smith
Peter Hansen [EMAIL PROTECTED] wrote:
 B. Don't bother trying, because even if the MTU is large enough there is 
 absolutely no guarantee that the packet will stay intact all the way 
 through the network anyway (even if you use sendall() instead of send()).

This is true, but I'm generating the message being sent in very small 
chunks (often as small as 4 bytes at a time), and typically need to flush a 
packet out onto the network after a few dozen bytes.  Maybe at most a few 
hundred.  I don't know of any networks with MTU's smaller than that.  
Measurements show a 10-fold improvement in protocol throughput with large 
packets vs. small ones.  The only question is what's the most efficient way 
in Python to generate the large packets.

 So fixing your design not to require this appears to be the only viable 
 solution.

My design is not broken.  I'm writing code to drive a pre-existing binary 
communications protocol.  It is what it is.  The functionality I seek 
exists at the Unix system call level (writev, sendmsg), but doesn't appear 
to be exposed in the Python socket API.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scatter/gather on sockets?

2006-04-01 Thread Roy Smith
In article [EMAIL PROTECTED],
 Anthony Greene [EMAIL PROTECTED] wrote:

 On Sat, 01 Apr 2006 14:56:02 -0500, Roy Smith wrote:
 
  I've got a bunch of strings in a list:
  
  vector = []
  vector.append (foo)
  vector.append (bar)
  vector.append (baz)
  
  I want to send all of them out a socket in a single send() call, so
  they end up in a single packet (assuming the MTU is large enough).  I
  can do:
  
  mySocket.send (.join (vector))
  
  but that involves creating an intermediate string.  Is there a more
  efficient way, that doesn't involve that extra data copy?
 
 Is sendall() what you're looking for?

No.  Sendall() is actually what I'm using now.  It handles the other side 
of the issue; issuing repeated send() calls if the system fragments your 
buffer.  I'm trying to aggregate lots of small buffers into one large one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between 'is' and '=='

2006-04-03 Thread Roy Smith
Adam DePrince  [EMAIL PROTECTED] wrote:
 It just happens that the
logical operation 

 (a is b ) - (a == b )

is always True.  

Only for small values of always.  You can always do pathological
things with operators:

class Foo:
def __eq__ (self, other):
return False

f = Foo()
print f is f
print f == f

frame:play$ ./is.py
True
False

This may even be useful.  What if you were trying to emulate SQL's
NULL?  NULL compares false to anything, even itself.  To test for
NULLness, you have to use the special is NULL operator.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange problem when running python code

2006-04-04 Thread Roy Smith
ishtar2020 [EMAIL PROTECTED] wrote:
I've been writing my very first application in Python and everything is
running smoothly, except for a strange problem that pops up every once
in a while. I'm sure is the kind
of newbie thing every seasoned programmer knows.

Nobody here has a crystal ball.  Please post your code, tell us what
changes you made, and cut-and-paste the entire error message and the
associated stack trace.


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


Re: ``pickling'' and ``unpickling''

2006-04-06 Thread Roy Smith
In article [EMAIL PROTECTED],
 Lonnie Princehouse [EMAIL PROTECTED] wrote:

 Pickling is the Python term for serialization.   See
 http://en.wikipedia.org/wiki/Serialization
 
 Suppose you want to save a Python object x to a file...
 
 output_file = open('my_pickle', 'wb') # open a file
 
 import pickle
 pickle.dump(x, output_file)  # write x to the file
 output_file.close()
 
 ... and to restore x from the file:
 
 input_file = open('my_pickle','rb')
 x = pickle.load(input_file)
 input_file.close()

I used to use pickles a lot for making scripts start up faster by cacheing 
intermediate results.  On startup, I had to read and parse a bunch of large 
text files and build a complicated in-memory database out of them.  That 
took something like 10 seconds.  However, the text files very rarely 
changed.  To save startup time, I read the files in once, and pickled the 
database in a file.  On subsequent runs, I'd just read in the pickle, which 
took a fraction of a second.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorators, Identity functions and execution...

2006-04-09 Thread Roy Smith
Steven D'Aprano [EMAIL PROTECTED] wrote:

 On Sun, 09 Apr 2006 08:52:18 -0700, Carl Banks wrote:
 
  it's more important
  to respect community standards than to stick to some silly preference
  you have.
 
 What happens when the community standard is a silly preference? I object
 to the suggestion that community standards (that is, a standard not even
 designed by a committee, merely evolved by a mob) is necessarily worthy of
 respect.

Design by committee has far from a stellar track record.  On the Internet, 
most of the really good stuff has come from the mobs.

 As it turns out, regarding this particular silly preference (community
 or private), I always remember that communication is the purpose of email
 (and, believe it or not, Usenet), and the use of tabs in some buggy
 news readers can cause the failure of communication. Hence I use spaces
 when posting code.

As you should.  It matters not whether news readers that can't handle tabs 
are buggy or not.  The fact is that they exist.  One of the most basic 
maxims on the Internet has always been, Be liberal in what you accept, be 
conservative in what you produce.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how relevant is C today?

2006-04-09 Thread Roy Smith
In article [EMAIL PROTECTED],
 gregarican [EMAIL PROTECTED] wrote:

 Here are a few languages I recommend most programmers should at least
 have a peek at:
 
 1) Smalltalk - The original object oriented programming language.
 Influenced anything from Mac/Windows GUI to Java language. Terse, clean
 syntax. IDE rolled into an operating system rolled into a set of core
 libraries.
 2) Lisp - Along with FORTRAN, one of the oldest programming languages
 still in use. Pure functional programming model that is extensible and
 has many derivatives. Great for mathematical purposes. Easy to learn if
 you can get past all of the nested parenthesis :-)
 3) C - The Latin of modern programming languages. Used in low level
 tasks (e.g. - hardware drivers) as well as larger projects (e.g. -
 operating systems and other programming languages). Logcal, explicit
 flow albeit a bit wordy.
 
 I have worked in C and Smalltalk for awhile now and just starting to
 pickup Lisp. Knowing different languages can help you approach problems
 with a fresh perspective. I prefer to code in Ruby and Python but can
 use these languages a certain way given the angles I have picked up
 elsewhere...

I would add to that list PostScript.  Most people think of it as just 
format for print files, but it's a a real general-purpose programming 
language, and a cool one at that (with an clear similarity to FORTH).  The 
stack-based paradigm can be a bit mind bending if you're not used to it, 
but bending your mind is the whole point of learning something new.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About classes and OOP in Python

2006-04-10 Thread Roy Smith
fyhuang [EMAIL PROTECTED] wrote:
 I've been wondering a lot about why Python handles classes and OOP the
 way it does. From what I understand, there is no concept of class
 encapsulation in Python, i.e. no such thing as a private variable. Any
 part of the code is allowed access to any variable in any class, and
 even non-existant variables can be accessed: they are simply created.
 I'm wondering what the philosophy behind this is, and if this
 behaviour is going to change in any future release of Python.

There are advantages and disadvantages to C++/Java style encapsulation 
using private data.  The advantages you (apparently) already know.  The 
disadvantage is added complexity.  There's a saying, You can't have a bug 
in a line of code you never write.  By having to write all those getter 
and setter methods, you just add bulk and complexity.

That being said, you can indeed have private data in Python.  Just prefix 
your variable names with two underscores (i.e. __foo), and they effectively 
become private.  Yes, you can bypass this if you really want to, but then 
again, you can bypass private in C++ too.   You can also intercept any 
attempt to access Python attributes by writing __getattr__() and 
__setattr__() methods for your class.

 It seems to me that it is difficult to use OOP to a wide extent in
 Python code because these features of the language introduce many
 inadvertant bugs. For example, if the programmer typos a variable name
 in an assignment, the assignment will probably not do what the
 programmer intended.

Yes, that is is a risk.  Most people deal with that risk by doing a lot of 
testing (which you should be doing anyway).  If you really want to, you can 
use the __slots__ technique to prevent this particular bug from happening 
(although the purists will tell you that this is not what __slots__ was 
designed for).

 My main question is that of why Python chooses to use this type of OOP 
 model and if it is planned to change.

It sounds like you are used to things like C++ and Java, which are very 
static languages.  Everything is declared at compile time, and there are 
many safeguards in the language to keep you from shooting yourself in the 
foot.  They problem is, they often prevent you from getting any useful work 
done either; you spend most of your time programming the language, not the 
problem you are trying to solve.

In the past week, I've had two conversations with people about the nuances 
of C++ assignment operators.  None of our customers give two figs about 
assignment operators.  Getting them right is just a detour we need to take 
to keep our software from crashing.  With Python, I write a = b and trust 
that it does the right thing.  That lets me concentrate on adding value 
that our customer will see.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Roy Smith
In article [EMAIL PROTECTED],
 Pierre Quentel [EMAIL PROTECTED] wrote:

 I added an entry in Wikipedia for information, just like other Python
 web frameworks have already done. If the style doesn't fit Wikipedia's
 I'm sorry and willing to learn how to improve it ; the reason I read
 was Obvious, if elaborate, link spam. Really should be speedied, but I
 can't find a CSD that fits this. I don't really understand why it's
 called a spam, I don't know what a CSD is and I don't know either who
 deleted the prod template, not me anyway. I'll take wikipedia people's
 advice into account anyway

Hi Pierre,

As the guy who put the deletion notice on the article, let me explain how 
this works, and why I did what I did.  My apologies if my comment appeared 
abrupt or rude. 

CSD stands for Criteria for Speedy Deletion.  It's a set of specific 
rules describing types of articles which don't fit Wikipedia's charter.  If 
an article fits one of the CSD rules, any Wikipedia admin (which I am), can 
delete the article on their own, with no further ado.  Hundreds of articles 
a day are deleted under CSD.  Your article did not meet any of those 
specific rules.  You can read more at http://en.wikipedia.org/wiki/Wp:csd

CSD or not, I still felt that the article was not appropriate for 
Wikipedia.  Wikipedia is an encyclopedia; it's meant to collect, organize, 
and present information about significant things.  It is explicitly NOT 
meant to be used as a tool to promote things, even things which are being 
given away for free.  Wikipedia has become one of the most well-known web 
sites on the Internet, and is thus often used by people with things to 
promote as an easy way to get some free publicity.  That is what your 
article looked like.  I thus took the step of proposing that it be deleted.  
I used a relatively new process which gives people 5 days to object to the 
proposal, and if anybody does, the article is kept.  That's what happened 
here.  It also prompted it to get cleaned up a lot, which is a Good Thing.

The next step I could take would be to bring the article to what's called 
AFD, or Articles For Deletion.  At that point, there would be a more formal 
debate about the pros and cons of the article vis-a-vis Wikipedia's 
charter, and finally some other (neutral) admin would come along and make a 
final determination.  The article has improved enough that I don't think 
I'm going to do that.  It still concerns me that you appear to be using 
Wikipedia to promote your own work, but I'll leave that up to other editors 
to decide what they want to do.

Please don't misunderstand my actions.  I'm all for promoting Python, and 
your Karrigel system looks interesting.  Wikipedia is just not the correct 
forum for such promotion.  There is a fine line between promotion and 
documentation.  It's often difficult to know where that line is, especially 
when you're personally close to a project.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ancient projectiles (was: Muzzle Velocity (was: High resolution sleep (Linux))

2007-05-26 Thread Roy Smith
In article [EMAIL PROTECTED], [EMAIL PROTECTED] (Cameron Laird) 
wrote:

 Hmmm; now you've got me curious.  What *were* the first
 composite projectiles?

Fetchez la Vache!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-27 Thread Roy Smith
Ben Finney [EMAIL PROTECTED] wrote:
 Is C no longer a major language? The long-standing convention there
 is for lower_case_with_underscores.

Which dates back to the days of ASR-33's which only had one case (upper 
case, as a matter of fact).  Does nobody else remember C compilers which 
accepted \( and \) for { and }?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-28 Thread Roy Smith
In article [EMAIL PROTECTED],
 Steven Bethard [EMAIL PROTECTED] wrote:

 Stefan Sonnenberg-Carstens wrote:
  Paul McGuire schrieb:
  I'm starting a new thread for this topic, so as not to hijack the one
  started by Steve Howell's excellent post titled ten small Python
  programs.
 
  In that thread, there was a suggestion that these examples should
  conform to PEP-8's style recommendations, including use of
  lower_case_with_underscores style for function names.  I raised some
  questions about this suggestion, since I liked the names the way they
  were, but as a result, part of the discussion has drifted into a
  separate track about PEP-8, and naming styles.
 
  I prefer mixedCaseStyle, and I think that should be standard, as this 
  style is commonly
  used in all major languages , for example Java,C++,C#.
  It shortens the identifiers but leaves the meaning intact.
 
 The argument for under_score_names is usually that non-native speakers 
 can more easily find the word boundaries. Not being a non-native speaker 
 ;-) I can't verify that one, but it's pretty plausible given the current 
 amount of money spent on research on automatic word-segmentation for 
 languages like Chinese. =)
 
 STeVe

I've gone through a few different flavors of composite name schemes over 
the years (starting with FORTRAN's 6 upper case character limit).  When 
first exposed to camelCase, I thought it was horrible.  Eventually, I came 
to like it.

On the other hand, I'm convinced that words_with_underscores, is easier to 
read.  This is especially true when abbreviations creep into variable 
names.  It's certainly easier to parse ip_address as compared to IPAddress.  
Same with snmp_manager vs SNMPManager.

I really like lisp's convention of using dashes instead of underscores, 
i.e. ip-address and snmp-manager.  I think the only reason most languages 
don't use that is the parsing ambiguity, but if you required white space 
around all operators, then ip-address would unambiguously be a variable 
name and ip - address would be a subtraction expression.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-30 Thread Roy Smith
Dave Hansen [EMAIL PROTECTED] wrote:

 On May 27, 3:25 pm, Roy Smith [EMAIL PROTECTED] wrote:
  Ben Finney [EMAIL PROTECTED] wrote:
   Is C no longer a major language? The long-standing convention there
   is for lower_case_with_underscores.
 
  Which dates back to the days of ASR-33's which only had one case (upper
 
 The date is about right (actually, a little early: ASR-33, 1965; C,
 about 1970), but you can't program C on an ASR-33.

Damn, I wish I had known that at the time :-)

 Keywords are all
 lower case, and always have been.  IF is a syntax error...

I doubt it still works on anything made today, but back in those days, if 
you typed your login name in all upper case, the terminal was put into 
lcase mode.  Upper case on input was automatically converted to lower case.  
You typed IF, the C compiler saw if, and it all worked.  Including \( 
and \) for curly braces.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Pop Quiz

2007-06-01 Thread Roy Smith
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 1. Do you like Python?

Yes

 2. Do you think Python is good?

Yes

 3. Do you think Python is real good?

Yes

 4. What is your favorite version of Python?

Whichever version it was that added string methods.

 5. Because of Python, do you think it will be easier to take over the
 world? If so, when? If not, when?

Just as soon as I get my orbiting brain lasers back on line.

 7. How many Z80 assembly language programmers does it take to equal
 one Python guru?

Trick question, the Z80 was a figment of your imagination.

 Essay: C++ is better than C, agree or disagree? (four word maximum)

STL compile error diagnostics.

 Bonus: A rabbi walks into a bar while nursing a baby goat. He is
 closely followed by a priest, and a Perl hacker. Explain.

The bartender says, What is this, some kind of a joke?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Pop Quiz

2007-06-02 Thread Roy Smith
In article [EMAIL PROTECTED],
 Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:

 In [EMAIL PROTECTED], Roy Smith
 wrote:
 
  In article [EMAIL PROTECTED],
   [EMAIL PROTECTED] wrote:
  7. How many Z80 assembly language programmers does it take to equal
  one Python guru?
  
  Trick question, the Z80 was a figment of your imagination.
 
 http://en.wikipedia.org/wiki/Zilog_Z80

Wikipedia is a figment of your imagination.  And, having once had a 
Trash-80 (complete with audio cassette storage), I certainly hope the Z-80 
was also.


 
  Essay: C++ is better than C, agree or disagree? (four word maximum)
  
  STL compile error diagnostics.
 
 So do you agree or disagree!?  ;-)

Depends.  Are we talking four 32-bit words or four 64-bit words?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is 1 large Regex faster than 3 smaller ones?

2007-06-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 erikcw [EMAIL PROTECTED] wrote:

 Hi,
 
 I need to match 3 small strings in a small text file (about 200 words
 of text).
 
 Would it be faster to write 1 compiled regex that matches all 3
 substrings in one go, or to use 3 separate regular expressions to do
 the same job?
 
 Thanks!
 Erik

For a classic regex, the answer is one big one.  Matching against a regex 
takes time proportional to the number of characters of input.  One big 
regex will probably consume more memory, and may be slower to compile, but 
it should run faster.

On the other hand, there are a lot of things that pattern maching libraries 
accept these days under the guise of being a regex which are not strictly 
regexes in the classic sense.

From a purely practical point of view, if your input is only 200 words, 
it's likely that the search time will be insignificant no matter what you 
do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding unit tests in source files?

2007-06-17 Thread Roy Smith
I'm starting a new project and am thinking of embedding my unit tests
right in the source files.  I've used unittest before, and I'm happy
with it, but I've always used it with the source code in one file and
the unit tests in another.  I figure if I just put a

if __name__ == '__main__:
import unittest
blah, blah, blah

block at the end of each source file, I'll end up with a cleaner
project structure.  I can run the unit tests just by executing each
source file.  Any comments from people who have organized their Python
projects this way?  Did it work out well?

It seems like what you give up is the ability to aggregate tests in a
hierarchy of test suites.  In theory, that sounds like something you
might want to do, but in practice, I've never found it that useful, so
I don't think I'll miss it.

I know about doctest, but I'm happy with unittest and don't see any
reason to change.

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


Re: strip() 2.4.4

2007-06-21 Thread Roy Smith
In article [EMAIL PROTECTED],
 Nick [EMAIL PROTECTED] wrote:

 strip() isn't working as i expect, am i doing something wrong -
 
 Sample data in file in.txt:
 
 'AF':'AFG':'004':'AFGHANISTAN':'Afghanistan'
 'AL':'ALB':'008':'ALBANIA':'Albania'
 'DZ':'DZA':'012':'ALGERIA':'Algeria'
 'AS':'ASM':'016':'AMERICAN SAMOA':'American Samoa'
 
 
 Code:
 
 f1 = open('in.txt', 'r')
 
 for line in f1:
 print line.rsplit(':')[4].strip('),
 
 Output:
 
 Afghanistan'
 Albania'
 Algeria'
 American Samoa'
 
 Why is there a apostrophe still at the end?

No clue, I can't reproduce it, but here's some ideas to try.

1) It helps to give more information.  Exactly what version of python are 
you using?  Cut-and-paste what python prints out when you start it up 
interactively, i.e.:

Python 2.4 (#1, Jan 17 2005, 14:59:14) 
[GCC 3.3.3 (NetBSD nb3 20040520)] on netbsd2

More than likely, just saying 2.4 would tell people all they need to 
know, but it never hurts to give more info.

2) Try to isolate what's happening.  Is the trailing quote really in the 
string, or is print adding it?  Do something like:

temp = line.rsplit(':')[4].strip(')
print repr (temp[0])

and see what happens.

3) Are you sure the argument you're giving to strip() is the same character 
that's in the file?  Is it possible the file has non-ascii characters, such 
as smart quotes?  Try printing ord(temp[0]) and ord(temp(')) and see if 
they give you the same value.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Modernization of Emacs

2007-06-21 Thread Roy Smith
In article [EMAIL PROTECTED], David Kastrup [EMAIL PROTECTED] 
wrote:

 Kaldrenon [EMAIL PROTECTED] writes:
 
  I'm very, very new to emacs. I used it a little this past year in
  college, but I didn't try at all to delve into its features. I'm
  starting that process now, and frankly, the thought of it changing -
  already- upsets me. I don't feel like the program ought to change in
  order to accommodate me.
 
 Actually, the E in Emacs stands for extensible.  Part of the
 appeal of Emacs is that you can change it to accommodate you.

Actually, the E in Emacs stands for Editor.  And the macs part stands 
for Macros.  As in Editor Macros.  It started out as a bunch of macros 
written in TECO.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposed new PEP: print to expand generators

2006-06-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 James J. Besemer [EMAIL PROTECTED] wrote:

 I propose that we extend the semantics of print such that if the object to 
 be printed is a generator then print would iterate over the resulting 
 sequence of sub-objects and recursively print each of the items in order.

I believe the functionality you desire already exists, or something very 
close to it, in the pprint (pretty printer) module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary .keys() and .values() should return a set [with Python 3000 in mind]

2006-07-01 Thread Roy Smith
Nick Vatamaniuc [EMAIL PROTECTED] wrote:
 But there is a side note:  old code that assumed a particular ordering 
 of the keys or values is broken anyway.

From a testing point of view, it would be interesting if there was a flag 
which said, Deliberately change everything which isn't guaranteed to be a 
specific way.  So, for example, dict.keys() would return a list in reverse 
order of how it normally does it (even if it cost more to do it that way).  
An alternate hash key generator would be slipped into place.  Floating 
point math would get a little noise added to the least significant bits.  
And so on.  Might be interesting to see what sorts of bugs that would shake 
out from user code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check if the connectivity is via Ethernet or dial-up

2006-07-08 Thread Roy Smith
In article [EMAIL PROTECTED],
 jb [EMAIL PROTECTED] wrote:

 Hi all:
 
 I was just wondering if there is a way to check (using python
 scripting) whether the computer's connectivity is via Dial-up or
 LAN/Ethernet adaptor? Is there a way in python to check the status of
 all available Ethernet adaptors?  If not is there a way to achieve this
 by  just checking some network parameters using System module?.

The best I could suggest is get the pysnmp module, and that to poke around 
in the interface table (assuming your box is running an SNMP agent).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best command for running shell command

2006-07-11 Thread Roy Smith
In article [EMAIL PROTECTED],
 Donald Duck [EMAIL PROTECTED] wrote:

 I'm a little bit confused about what is the best way to run a shell command, 
 if I want to run a command like
 
   xx -a -b  yy
 
 where I'm not interested in the output, I only want to make sure that the 
 command was executed OK. How should I invoke this (in a Unix/linux 
 environment)?

The most straight-forward way would be:

import os
status = os.system (xx -a -b  yy)
if status == 0:
   print it worked
else:
   print it failed

You might also want to look at the new (in 2.4) subprocess module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SNMP agent

2007-04-06 Thread Roy Smith
[EMAIL PROTECTED] (Cameron Laird) wrote:
 I understand the sentiment; in principle, it shouldn't be hard
 to write a library which supports construction of SNMP agents
 in Python.  I'm aware of no one who has done so publicly, though.

I've used pysnmp (http://pysnmp.sourceforge.net/) in a test environment for 
a while.  Only the manager side, never tried to implement an agent.  It's 
pure python, so it's very portable.  In theory, that also means it's not 
very fast, but for what I've ever wanted it for, it was plenty fast enough.

The latest NetSNMP release apparently now includes a python binding 
(http://www.net-snmp.org/docs/NEWS.html).  I have not had a chance to use 
it, but it sounds good.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check if a string is empty in python?

2007-05-02 Thread Roy Smith
In article [EMAIL PROTECTED],
 Dustan [EMAIL PROTECTED] wrote:

 On May 2, 5:50 pm, Steven D'Aprano
 [EMAIL PROTECTED] wrote:
  On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote:
   How to check if a string is empty in python?
   if(s == ) ??
 
  In no particular order, all of these methods will work:
 
  # test s is equal to another empty string
  if s == :
 
  # assuming s is a string, test that it is empty
  if not s:
 
  # test s is a string and it is empty
  if isinstance(s, str) and not s:
 
  # test s has length 0
  if len(s) == 0:
 
  # test the length of s evaluates as false
  if not len(s):
 
  # a long way to test the length of s
  if s.__len__()  1:
 
  # a stupid way to test s is empty
  if bool(s) == False:
 
  # a REALLY stupid way to test s is empty
  if (bool(s) == False) == True:
 
 LOL
 
  # test that appending s to itself is itself
  if s+s == s:
 
  # test that s has none of any character
  if not filter(None, [1 + s.find(chr(n)) for n in range(256)]):
 
  That last one is really only good for wasting CPU cycles.
 
 and the other ones are... ?
 
  --
  Steven.

s.join(foo) == foo

for c in s:
   raise it's not empty
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check if a string is empty in python?

2007-05-03 Thread Roy Smith
In article [EMAIL PROTECTED],
 Ant [EMAIL PROTECTED] wrote:

 On May 3, 5:59 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
  Steven D'Aprano [EMAIL PROTECTED] wrote:
   On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote:
 
for c in s:
   raise it's not empty
 
   String exceptions are depreciated and shouldn't be used.
 
  http://docs.python.org/api/node16.html
 
  They're actually deprecated, not depreciated.
 
 In Steven's defence, string exceptions *are* probably worth less, as
 there's no longer such a demand for them.

You just wait until they start showing up on Antiques Roadshow :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Don't use __slots__! (was Re: dicts vs classes)

2006-07-25 Thread Roy Smith
Guido sez:

 __slots__ is a terrible hack with nasty, hard-to-fathom side
 effects that should only be used by programmers at grandmaster and
 wizard levels. Unfortunately it has gained an enormous undeserved
 popularity amongst the novices and apprentices, who should know
 better than to use this magic incantation casually.

But, if they are novices, why should they be expected to know better?

I just re-read http://docs.python.org/ref/slots.html#l2h-217 and don't
see anyplace where it says, Warning: for use by wizards only.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find difference in years between two dates?

2006-07-26 Thread Roy Smith
thebjorn [EMAIL PROTECTED] wrote:

   def age(born):
   now = date.today()
   birthday = date(now.year, born.month, born.day)
   return now.year - born.year - (birthday  now and 1 or 0)

I don't get that last line.  There's two things in particular that are 
puzzling me.

1) What does birthday  now mean?  It sounds like you haven't been born 
yet.

2) I find the and 1 or 0 part very confusing.  I can't remember all the 
minor rules about operator precedence, but I'm sure this works out to some 
clever hack involving boolean short-circuit evaluation to get around the 
lack of a ternary operator in python.  If I need to pull out the reference 
manual to decipher what an expression means, it's too complicated.  Try 
something like:

if birthday  now:
   return now.year - born.year - 1
else:
   return now.year - born.year

It takes up a little more space, but it's bog easy to understand without 
scratching your head or diving into the manual to refresh your memory of 
obscure language details.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Railroad track syntax diagrams

2006-08-01 Thread Roy Smith
Paul McGuire [EMAIL PROTECTED] wrote:
 For those who are not familiar with railroad syntax diagrams, they
 show a grammar's syntax using arrows and blocks, instead of BNF

I've always liked railroad diagrams.  Oracle used to use them (maybe
they still do?) in their SQL reference manuals.  I find them much
easier to understand than BNF.
-- 
http://mail.python.org/mailman/listinfo/python-list


<    1   2   3   4   5   6   7   8   9   10   >