Re: First python program, syntax error in while loop

2013-05-06 Thread Chris Angelico
On Mon, May 6, 2013 at 11:08 PM, Roy Smith  wrote:
> On the other hand, I've long since given up trying to remember operator
> precedence in various languages.  If I ever have even the slightest
> doubt, I just go ahead and put in the extra parens.

If I ever have even the slightest doubt, I just go ahead and type
" operator precedence" into a web search and check it :)
Aside from utter insanity like PHP's ternary operator being wrongly
associative, that covers pretty much everything.

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


Re: socket programming

2013-05-06 Thread Chris Angelico
On Tue, May 7, 2013 at 1:54 AM, Pedro  wrote:
> Thanks for the reply. I'm sending short strings as commands to my server 
> machine so the socket module seems to be doing the trick reliably. I'll try 
> to add Twisted to my arsenal though.
> Cheers

I've never used Twisted, so I can't say how good it is. All I know is
that what I learned about socket programming in C on OS/2 is still
valid on Windows and on Linux, and in every language I've ever used
(bar JavaScript and ActionScript, which are deliberately sandboxed and
thus don't have direct socket calls available). So take your pick: Go
with Twisted, and bind yourself to a particular library, or go with
BSD sockets, and do the work yourself. Like everything else in
programming, it's a tradeoff.

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


Re: First python program, syntax error in while loop

2013-05-06 Thread Chris Angelico
On Tue, May 7, 2013 at 6:11 AM, Terry Jan Reedy  wrote:
> On 5/6/2013 11:31 AM, Roy Smith wrote:
>>
>> In article ,
>> Chris Angelico   wrote:
>>> If I ever have even the slightest doubt, I just go ahead and type
>>> " operator precedence" into a web search and check it :)
>>
>>
>> Well, that solves the problem once, and it solves it for me.  I figure
>> if I'm not 100% sure, then maybe other people aren't 100% sure either,
>> and my adding the extra parens helps them too.
>
>
> If you keep the Python docs handy, on or off line, the Language manual
> Expressions chapter ends with this single page (but better formatted as a
> table than here). But I sometimes add parens for quickness or readability.
>
> or Boolean OR
> and Boolean AND

Actually, this is one exception. I tend to parenthesize any case where
there's a complex set of conditions and mixed AND and OR operations.
Part of the reason for this is that any expression that can be
affected by the precedence of and and or will most likely be fairly
long and/or complex anyway, so a few extra parens won't hurt.

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


Re: python backup script

2013-05-06 Thread Chris Angelico
On Tue, May 7, 2013 at 5:01 AM, MMZ  wrote:
> username = config.get('client', 'mmz')
> password = config.get('client', 'pass1')
> hostname = config.get('client', 'localhost')

Are 'mmz', 'pass1', and 'localhost' the actual values you want for
username, password, and hostname? If so, don't pass them through
config.get() at all - just use them directly. In fact, I'd be inclined
to just stuff them straight into the Database_list_command literal;
that way, it's clear how they're used, and the fact that you aren't
escaping them in any way isn't going to be a problem (tip: an
apostrophe in your password would currently break your script).

It's also worth noting that the ~/ notation is a shell feature. You
may or may not be able to use it in config.read().

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


Re: python backup script

2013-05-06 Thread Chris Angelico
On Tue, May 7, 2013 at 8:40 AM, MMZ  wrote:
> Thanks Chris. you are right.
> So I used them directly and removed configParser. The new error is:
>
> Traceback (most recent call last):
>   File "./bbk.py", line 11, in ?
> for database in os.popen(database_list_command).readlines():
> NameError: name 'database_list_command' is not defined

Python names are case-sensitive. If you create it with a capital D,
you can't reference it with a lower-case d. For consistency with the
rest of your code, I'd advise lowercasing it.

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


Re: Red Black Tree implementation?

2013-05-06 Thread Chris Angelico
On Tue, May 7, 2013 at 10:55 AM, duncan smith  wrote:
> Here's the text I usually prepend.
>
>
> ##Copyright (c) 2013 duncan g. smith
> ##
> ##Permission is hereby granted, free of charge, to any person obtaining a
> ##copy of this software and associated documentation files (the "Software"),
> ##to deal in the Software without restriction, including without limitation
> ##the rights to use, copy, modify, merge, publish, distribute, sublicense,
> ##and/or sell copies of the Software, and to permit persons to whom the
> ##Software is furnished to do so, subject to the following conditions:
> ##
> ##The above copyright notice and this permission notice shall be included
> ##in all copies or substantial portions of the Software.
> ##
> ##THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
> ##OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
> MERCHANTABILITY,
> ##FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
> ##THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
> ##OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
> ##ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
> ##OTHER DEALINGS IN THE SOFTWARE.
>
>
> Basically, "do what you want with it but don't blame me if it goes tits up".
> I'm happy to consider tidying it up a bit and using a more recognized form
> of licence.

Is that the MIT license? If not, consider using it; it's well known
and trusted. I haven't eyeballed yours closely but it looks extremely
similar, at least.

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


Re: First python program, syntax error in while loop

2013-05-07 Thread Chris Angelico
On Tue, May 7, 2013 at 4:10 PM, Mark Lawrence  wrote:
> On 07/05/2013 01:17, alex23 wrote:
>>
>> On May 6, 10:37 pm, Mark Lawrence  wrote:
>>>
>>> One of these days I'll work out why some people insist on using
>>> superfluous parentheses in Python code.  Could it be that they enjoy
>>> exercising their fingers by reaching for the shift key in conjunction
>>> with the 9 or 0 key?
>>
>>
>> One of these days I'll work out why some programmers consider typing
>> to be "effort".
>>
>
> I think it's very important to consider this aspect.  E.g. any one using
> dynamically typed languages has to put in more effort as they should be
> typing up their test code, whereas people using statically typed languages
> can simply head down to the pub once their code has compiled.

And those who are porting other people's code to a new platform have
weeks of work just to get ./configure to run, but after that it's
smooth...

Everything is variable.

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


Re: use python to split a video file into a set of parts

2013-05-07 Thread Chris Angelico
On Tue, May 7, 2013 at 9:15 PM, iMath  wrote:
> I use the following python code to split a FLV video file into a set of parts 
> ,when finished ,only the first part video can be played ,the other parts are 
> corrupted.I wonder why and Is there some correct ways to split video files

Most complex files of this nature have headers. You're chunking it in
pure bytes, so chances are you're disrupting that. The only thing you
can reliably do with your chunks is recombine them into the original
file.

> import sys, os
> kilobytes = 1024
> megabytes = kilobytes * 1000
> chunksize = int(1.4 * megabytes)   # default: roughly a floppy

Hrm. Firstly, this is a very small chunksize for today's files. You
hard-fail any file more than about 13GB, and for anything over a gig,
you're looking at a thousand files or more. Secondly, why are you
working with 1024 at the first level and 1000 at the second? You're
still a smidge short of the 1440KB that was described as 1.44MB, and
you have the same error of unit. Stick to binary kay OR decimal kay,
don't mix and match!

> print(chunksize , type(chunksize ))

Since you passed chunksize through the int() constructor, you can be
fairly confident it'll be an int :)

> def split(fromfile, todir, chunksize=chunksize):
> if not os.path.exists(todir):  # caller handles errors
> os.mkdir(todir)# make dir, read/write 
> parts
> else:
> for fname in os.listdir(todir):# delete any existing files
> os.remove(os.path.join(todir, fname))

Tip: Use os.mkdirs() in case some of its parents need to be made. And
if you wrap it in try/catch rather than probing first, you eliminate a
race condition. (By the way, it's pretty dangerous to just delete
files from someone else's directory. I would recommend aborting with
an error if you absolutely must work with an empty directory.)

> input = open(fromfile, 'rb')   # use binary mode on 
> Windows

As a general rule I prefer to avoid shadowing builtins, but it's not
strictly a problem.

> filename = os.path.join(todir, ('part{}.flv'.format(partnum)))
> assert partnum <=  # join sort fails if 5 
> digits
> return partnum

Why the assertion? Since this is all you do with the partnum, why does
it matter how long the number is? Without seeing the join sort I can't
know why that would fail; but there must surely be a solution to this.

> fromfile = input('File to be split: ')   # input if clicked

"clicked"? I'm guessing this is a translation problem, but I've no
idea what you mean by it.

What you have seems to be a reasonably viable (not that I tested it or
anything) file-level split. You should be able to re-join the parts
quite easily. But the subsequent parts are highly unlikely to play.
Even if you were working in a format that had no headers and could
resynchronize, chances are a 1.4MB file won't have enough to play
anything. Consider: A 1280x720 image contains 921,600 pixels;
uncompressed, this would take 2-4 bytes per pixel, depending on color
depth. To get a single playable frame, you would need an i-frame (ie
not a difference frame) to start and end within a single 1.4MB unit;
it would need to compress 50-75% just to fit, and that's assuming
optimal placement. With random placement, you would need to be getting
87% compression on your index frames, and then you'd still get just
one frame inside your chunk. That's not likely to be very playable.

But hey. You can stitch 'em back together again :)

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


Re: Why do Perl programmers make more money than Python programmers

2013-05-07 Thread Chris Angelico
On Tue, May 7, 2013 at 11:22 PM, jmfauth  wrote:
> There are plenty of good reasons to use Python. There are
> also plenty of good reasons to not use (or now to drop)
> Python and to realize that if you wish to process text
> seriously, you are better served by using "corporate
> products" or tools using Unicode properly.

There are plenty of good reasons to use Python. One of them is the
laughs you can get any time jmf posts here. There are also plenty of
good reasons to drop Python. One of them is because corporate products
like Microsoft Visual Studio are inherently better specifically
because they cost you money, and there's no way that something you
paid nothing for can ever be as good as that. Plus, you get to write
code that works on only one platform, and that's really good. Finally,
moving off Python would mean you don't feel obliged to respond to jmf,
which will increase your productivity measurably.

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


Re: First python program, syntax error in while loop

2013-05-07 Thread Chris Angelico
On Tue, May 7, 2013 at 10:44 PM, Ombongi Moraa Fe
 wrote:
> My first language was Pascal. It was at a time in 2005 when computers were
> finally becoming popular in Africa and our year was the first time a girls
> school from our Province did a computer coursework for National Exams. (That
> was such an achievement *sigh*)
>
> "The teacher said ... Good Programming Practice ... Use parentheses to
> format code.. or I will deduct a point from your work when I feel like it."
>
> Cant seem to let go of the behavior. I use parentheses in all languages.

Pretty much all such blanket advice is flawed. I cannot at present
think of any example of a "Good Programming Practice" suggestion that
doesn't have its exceptions and caveats. The only ones that don't are
the ones that get codified into language/syntax rules, and even there,
most of them have their detractors. Python's indentation rule is a
prime example; most people follow the advice to always indent blocks
of code, Python makes it mandatory, and some people hate Python for
it. (And yes, there have been times when I've deliberately misindented
a block of C code, because it made more logical sense that way. I can
quote examples if you like.)

The only principle that you should follow is: Think about what you're
doing. Everything else is an elaboration on that. [1]

ChrisA
[1] Matthew 22:37-40 :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why sfml does not play the file inside a function in this python code?

2013-05-07 Thread Chris Angelico
On Wed, May 8, 2013 at 12:57 AM, MRAB  wrote:
> Also, please read this:
>
> http://wiki.python.org/moin/GoogleGroupsPython
>
> because gmail insists on adding extra linebreaks, which can be somewhat
> annoying.

Accuracy correction: It's nothing to do with gmail, which is what I
use (via python-list subscription). It's just Google Groups.

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


Re: Making safe file names

2013-05-07 Thread Chris Angelico
On Wed, May 8, 2013 at 8:18 AM, Fábio Santos  wrote:
> I suggest Base64. b64encode
> (http://docs.python.org/2/library/base64.html#base64.b64encode) and
> b64decode take an argument which allows you to eliminate the pesky "/"
> character. It's reversible and simple.

But it doesn't look anything like the original.

I'd be inclined to go for something like quoted-printable or
URL-encoding; special characters become much longer, but ordinary
characters (mostly) stay as themselves.

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


Re: cello library

2013-05-08 Thread Chris Angelico
On Wed, May 8, 2013 at 7:39 PM, Mark Lawrence  wrote:
> Hi folks,
>
> I thought some of you might find this interesting [link redacted]

If this is a legit post, can you please elaborate on just _why_ we
would find it interesting? I'm leery of clicking random links like
that without at least some indication. It could be some cool Python
library, or it could be something relating to music, or it could be a
malicious site ready to compromise my browser and your Yahoo account
was compromised to send spam.

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


Re: MySQL Database

2013-05-08 Thread Chris Angelico
On Thu, May 9, 2013 at 4:52 AM, Kevin Holleran  wrote:
> Will using db_c to update the database mess up the loop that is cycling
> through db_c.fetchall()?

Nope; fetchall() returns a list, which you're then iterating over.
Nothing the database does can disrupt that.

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


Re: cello library

2013-05-08 Thread Chris Angelico
On Thu, May 9, 2013 at 7:06 AM, Terry Jan Reedy  wrote:
> Legitimate request, like some I have made of others. Since I trust Mark:

It's actually nothing to do with trusting Mark. I've often seen posts
from addresses of people I trust, but with links that I definitely
would not want to click... and Mark posts from Yahoo, which is one of
the common targets of that sort of attack.

Anyway, a little context would have solved the whole thing.

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


Re: Style question -- plural of class name?

2013-05-08 Thread Chris Angelico
On Thu, May 9, 2013 at 6:20 AM, Roy Smith  wrote:
> "A list of FooEntry's"

Only if you put another apostrophe in:

"A list of 'FooEntry's"

But the delimited style is almost never of use. I'd go for this only
if there were some sort of automated markup being applied - if the
word FooEntry were turned into a hyperlink or something.

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


Re: Making safe file names

2013-05-08 Thread Chris Angelico
On Thu, May 9, 2013 at 10:16 AM, Roy Smith  wrote:
> Pro-tip, guys.  If you want to form a band, and expect people to be able
> to find your stuff in a search engine some day, don't play cute with
> your name.

It's the modern equivalent of names like Catherine Withekay.

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


Re: object.enable() anti-pattern

2013-05-08 Thread Chris Angelico
On Thu, May 9, 2013 at 3:37 PM, Steven D'Aprano
 wrote:
> I can see use-cases for separating "make it go" from initialisation. It
> all depends on what you might want to do to the object before making it
> go. If the answer is "Nothing", then there is no reason not to have the
> constructor make it go. If the answer is, "Well, sometimes we need to do
> things to the object before making it go", then it makes sense to
> separate the two:
>
> blob = MyBlob(arg1, arg2, agr3)
> blob.poke("with a stick")
> blob.append(data)
> blob.foo = "spam"
> blob.make_it_go()

Example use-case: Most GUI frameworks. You create a window, then
populate it, then show it. When you create the window object in
Python, you expect an actual window to exist, it should have its
handle etc. So it's still the same thing; the object is fully created
in its constructor.

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


Re: Append to python List

2013-05-09 Thread Chris Angelico
On Thu, May 9, 2013 at 4:36 PM, RAHUL RAJ  wrote:
> output=[x for x in sample2 if x not in output]
>
> output=[]
> for x in sample2:
>   if x not in output:
>  output.append(x)

The first one constructs a list, then points the name 'output' at it.
The second one builds up a list, with 'output' pointing at it all the
way. Your first one is more like:

sample2 = [x+y for x in range(1,10) for y in range(1,10) if x!=y]
output=[]
_temp=[]
for x in sample2:
  if x not in output:
 _temp.append(x)
output=_temp

You may want to consider using a set, instead.

>>> {x+y for x in range(1,10) for y in range(1,10) if x!=y}
{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}

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


Re: Urgent:Serial Port Read/Write

2013-05-09 Thread Chris Angelico
On Fri, May 10, 2013 at 1:35 AM, chandan kumar  wrote:
>
> Hi all,
> I'm new to python and facing issue using serial in python.I'm facing the 
> below error
>
> ser.write(port,command)
> NameError: global name 'ser' is not defined
>
> Please find the attached script and let me know whats wrong in my script and 
> also how can i read data from serial port for the  same script.

You're assigning to 'ser' inside OpenPort(), but then trying to use it
in WriteSerialData(). You'll need to declare 'global ser' in OpenPort
to make this work.

Alternatively, you may want to cut down on the number of functions you
have, since they're called in only one place anyway and have to share
state.

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


Re: Urgent:Serial Port Read/Write

2013-05-09 Thread Chris Angelico
On Fri, May 10, 2013 at 1:35 AM, chandan kumar  wrote:
> Please find the attached script and let me know whats wrong in my script
> and also how can i read data from serial port for the  same script.

Don't do this:

except serial.serialutil.SerialException:
print "Exception"
ser.close()

Just let it propagate up and show you a traceback. There is absolutely
no value in suppressing an exception only to print an unhelpful
message.

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


Re: object.enable() anti-pattern

2013-05-09 Thread Chris Angelico
On Fri, May 10, 2013 at 4:59 AM, Roy Smith  wrote:
> It's not hard to imagine a
> file class which could be used like:
>
> f = file("/path/to/my/file")
> f.delete()
>
> That would be a totally different model from the current python file
> object.  And then there would be plenty of things you might want to do
> to a file other than open it...
>
> file("/path/to/my/directory").chdir()
> file("/dev/sdf").mount("/var/lib/whatever")
> file("/mnt/swapfile").swapon()

Sure, you can imagine it. But what does it do that can't be done with
a moduleful of flat functions accepting strings? This makes sense in
Java, I guess, but why do it in Python?

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


Re: Message passing syntax for objects | OOPv2

2013-05-09 Thread Chris Angelico
On Fri, May 10, 2013 at 8:30 AM, Ian Kelly  wrote:
> On Thu, May 9, 2013 at 3:51 PM, Mark Janssen  
> wrote:
>> the community stays fractured.
>
> The open source community seems pretty healthy to me.  What is the
> basis of your claim that it is "fractured"?

The carpentry community is fractured. There are people who use
screwdrivers, and there are people who use hammers! Screws and nails
are such completely different things that we shouldn't try to use the
same language to discuss them.

>> Language "expressivity" can be measured.
>
> And the measurements can be endlessly debated.  Expressivity is not
> the sole measure of a programming language, though.

Every programming language can encode every program. It's fairly
straightforward to prove that a Python interpreter can be written in
Ruby, or a C interpreter in Lua; so there is no program that can be
expressed in one language and not in another (there will be apparent
exceptions, eg web-browser JavaScript cannot call on arbitrary C-level
functionality, but if the entirety of program code were written in C,
then it could all be interpreted by one C interpreter).

Larry Wall of Perl put it this way, in a State of the Onion address:

http://www.perl.com/pub/2007/12/06/soto-11.html
"""... Human languages are Turing complete, as it were.

Human languages therefore differ not so much in what you can say but
in what you must say. In English, you are forced to differentiate
singular from plural. In Japanese, you don't have to distinguish
singular from plural, but you do have to pick a specific level of
politeness, taking into account not only your degree of respect for
the person you're talking to, but also your degree of respect for the
person or thing you're talking about.

So languages differ in what you're forced to say. Obviously, if your
language forces you to say something, you can't be concise in that
particular dimension using your language. Which brings us back to
scripting.

How many ways are there for different scripting languages to be concise?
"""

In C, for example, you are forced to write explicit notation
representing {blocks; of; code;} and explicit characters separating;
statements;. In Python, on the other hand, you have to write out your
indentation. In Java, you state what exceptions you might throw. REXX
mandates that you annotate procedures with their list of exposed names
(effectively, non-local and global variables). So the expressivity of
a language can't be defined in terms of how many programs can be
written in it, but in how concisely they can be written - and that's
something that depends on specific design choices and how they align
with the code you're trying to write.

Compare these two snippets:

#!/bin/sh
pg_dumpall | gzip | ssh user@host 'gzip -d|psql'

#!/usr/bin/env python
words=input("Enter words, blank delimited: ")
lengths=[len(x) for x in words.split(" ")]
print("Average word length: %d"%int(sum(lengths)/len(lengths)))

Could you write each in the other's language? Sure! But it won't be as
concise. (The Python version of the shell script could cheat and just
call on the shell to do the work, but even that would add the
expressive overhead of "os.system".) This is why there are so many
languages: because each is good at something different.

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


Re: Message passing syntax for objects | OOPv2

2013-05-09 Thread Chris Angelico
On Fri, May 10, 2013 at 9:58 AM, alex23  wrote:
> On 10 May, 07:51, Mark Janssen  wrote:
>> Languages can reach for an optimal design (within a
>> constant margin of leeway).   Language "expressivity" can be measured.
>
> I'm sure that's great. I, however, have a major project going live in
> a few weeks and would rather just get something done.

Hmm, not really a fair argument there. A well-designed language lets
you "just get something done" far more efficiently than a
poorly-designed one. Being confident that similar objects behave
correspondingly when invoked the same way lets you write your code
without fiddling with minutiae, for instance. ("Hmm, I'll just switch
that from being a tuple to being a list, so I can modify this one
element." - code that indexes or iterates won't be affected.)

Now, whether or not it's worth _debating_ the expressiveness of a
language... well, that's another point entirely. But for your major
project, I think you'll do better working in Python than in machine
code.

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


Re: object.enable() anti-pattern

2013-05-09 Thread Chris Angelico
On Fri, May 10, 2013 at 12:30 PM, Steven D'Aprano
 wrote:
> I must admit I am astonished at how controversial the opinion "if your
> object is useless until you call 'start', you should automatically call
> 'start' when the object is created" has turned out to be.

I share your astonishment. This is a very simple point: If, after
constructing an object, the caller MUST call some method on it prior
to the object being of use, then better design is to embed that call
directly into the constructor. As always, it has its exceptions, but
that doesn't stop it being a useful rule.

The Path() equivalent would be:

p = Path()
p.set_path("/foo/bar")
if p.exists():
  pass

Even if you have a set_path() method, it makes good sense to symlink
it to __init__ to avoid this anti-pattern.

C level APIs often have these sorts of initialization requirements.

fd_set selectme;
FD_ZERO(&selectme);

This is because declaring a variable in C cannot initialize it.
Anything that *has* constructors should be using them to set objects
up... that's what they're for.

Where's the controversy?

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


Re: object.enable() anti-pattern

2013-05-09 Thread Chris Angelico
On Fri, May 10, 2013 at 1:19 PM, Mark Janssen  wrote:
>> I think where things went pear shaped is when you made the statement:
>>
 There is no sensible use-case for creating a file OBJECT unless it
 initially wraps an open file pointer.
>>
>> That's a pretty absolute point of view.  Life is rarely so absolute.
>
> In the old days, it was useful to have fine-grained control over the
> file object because you didn't know where it might fail, and the OS
> didn't necessarily give you give good status codes.  So being able to
> step through the entire process was the job of the progammers.

I don't know what you mean by the "old days", but a couple of decades
ago, there were no such things as "file objects". You call a function
to open a file, you get back a number. You explicitly close that by
calling another function and passing it that number. In fact, there is
no way to have a "file object" that doesn't have an open file
associated with it, because it's simply... a number.

> Now, with languages so high like python and hardware so common, it
> almost is never necessary, so he has some point.   A closed file
> pointer is useful from a OS-progamming point-of-view though because
> you generally never want to leave files open where they'd block other
> I/O.

I'm beginning to wonder if you and Dihedral are swapping notes.
Dihedral's been sounding fairly coherent lately.

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


Re: Message passing syntax for objects | OOPv2

2013-05-09 Thread Chris Angelico
On Fri, May 10, 2013 at 1:08 PM, Mark Janssen  wrote:
> On Thu, May 9, 2013 at 4:58 PM, alex23  wrote:
>> On 10 May, 07:51, Mark Janssen  wrote:
>>> You see Ian, while you and the other millions of coding practitioners
>>> have (mal)adapted to a suboptimal coding environment where "hey
>>> there's a language for everyone"  and terms are thrown around,
>>> misused, this is not how it needs or should be.
>>
>> Please cite your industry experience so we know this is a pragmatic
>> exercise for you and not a display of public onanism.
>
> "Industry experience"
>
> Do you know all the world's [industrial] leaders are endorsing an
> impossible path of endless, exponential growth on a finite planet?
>
> Is that who you answer to?

I don't answer to them. I also believe in a path of endless
exponential growth. Challenge: Create more information than can be
stored in one teaspoon of matter. Go ahead. Try!

The first hard disk I ever worked with stored 20MB in the space of a
5.25" slot (plus its associated ISA controller card). Later on we got
3.5" form factor drives, and I remember installing this *gigantic*
FOUR GIGABYTE drive into our disk server. Wow! We'll NEVER use all
that space! (Well, okay. Even then we knew that space consumption kept
going up. But we did figure on that 4GB lasting us a good while, which
it did.) Today, I can pop into Budget PC or MSY (or you folks in the
US could check out newegg) and pick up a terabyte of storage in the
same amount of physical space, or you can go 2.5" form factor and take
up roughly a fifth of the physical space and still get half a terabyte
fairly cheaply. So our exponential growth is being supported by
exponential increases in data per cubic meter. Between that and the
vast size of this planet, I don't think we really need to worry too
much about finite limits to IT growth.

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


Re: Message passing syntax for objects | OOPv2

2013-05-10 Thread Chris Angelico
On Fri, May 10, 2013 at 2:55 PM, Roy Smith  wrote:
> In article ,
>  Chris Angelico  wrote:
>
>> The first hard disk I ever worked with stored 20MB in the space of a
>> 5.25" slot (plus its associated ISA controller card).
>
> Heh.  The first hard disk I ever worked with stored 2.4 MB in 6U of rack
> space (plus 4 Unibus cards worth of controller).  That's not actually
> the first hard disk I ever used.  Just the first one I ever got to touch
> with my own hands.
>
> Did I mention that the air filters had to be changed a few times a year?
>
> Uphill both ways, in the snow, while beating off the dinosaurs with
> sticks.

Yeah, I'm pretty young. First computer I ever broke (the same one that
had the aforementioned 20MB drive) addressed a whole megabyte of
memory, 640KB of which was OK (we're left wondering whether anyone
would notice if ROM developed a fault), and I got to play around with
64KB of it in DEBUG.EXE. And yeah, I wrote code straight in DEBUG and
saved it and crashed the system. (Tip: If you want to write a device
driver, make sure you start with your dad happy with you.) Was good
fun. I heartily recommend the exercise, but... uhh... do consider
setting up a virtual machine first :)

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


Re: object.enable() anti-pattern

2013-05-10 Thread Chris Angelico
On Sat, May 11, 2013 at 12:37 AM, Roy Smith  wrote:
> I suppose, if I had a class like this, I would write a factory function
> which called the constructor and post-construction initializer.  And
> then I would make the constructor protected.

That sounds like a reasonable plan, with the possible exception of
protected. Since meeting Python, I've stopped using private and
protected anywhere.

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


Re: object.enable() anti-pattern

2013-05-10 Thread Chris Angelico
On Sat, May 11, 2013 at 12:54 AM, Roy Smith  wrote:
> In article ,
>  Chris Angelico  wrote:
>
>> On Sat, May 11, 2013 at 12:37 AM, Roy Smith  wrote:
>> > I suppose, if I had a class like this, I would write a factory function
>> > which called the constructor and post-construction initializer.  And
>> > then I would make the constructor protected.
>>
>> That sounds like a reasonable plan, with the possible exception of
>> protected. Since meeting Python, I've stopped using private and
>> protected anywhere.
>>
>> ChrisA
>
> Each language has its own set of best practices.  Trying to write C++
> code using Python patterns is as bad as trying to write Python code
> using C++ patterns.

Agreed, in generality. But what is actually gained by hiding data from
yourself? Compare:

class Foo
{
int asdf;
public:
Foo(int _asdf):asdf(_asdf) {}
int get_asdf() {return asdf;}
void set_asdf(int _asdf) {asdf=_asdf;}
void frob() {printf("Hi, I am %d\n",asdf);}
};

struct Foo
{
int asdf;
Foo(int _asdf):asdf(_asdf) {}
void frob() {printf("Hi, I am %d\n",asdf);}
};

Is there anything worse about the second one? Oh, and by logical
extension, here's something that doesn't (AFAIK) work in C++, but does
in another language that's syntactically similar:

class Foo(int asdf)
{
void frob() {write("Hi, I am %d\n",asdf);}
}

Now that's brevity. Why bother saying what's patently obvious? (Pike's
"class" keyword is like C++'s "struct", members are public by
default.)

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


Re: Unicode humor

2013-05-10 Thread Chris Angelico
On Sat, May 11, 2013 at 1:06 AM, jmfauth  wrote:
> On 8 mai, 15:19, Roy Smith  wrote:
>> Apropos to any of the myriad unicode threads that have been going on
>> recently:
>>
>> http://xkcd.com/1209/
>
> --
>
>
> This reflects a lack of understanding of Unicode.

By the skywriter, or by the two on the ground, or by Randall Munroe?

Or by jmf?

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


Re: Unicode humor

2013-05-10 Thread Chris Angelico
On Sat, May 11, 2013 at 1:24 AM, Ned Batchelder  wrote:
> On 5/10/2013 11:06 AM, jmfauth wrote:
>>
>> On 8 mai, 15:19, Roy Smith  wrote:
>>>
>>> Apropos to any of the myriad unicode threads that have been going on
>>> recently:
>>>
>>> http://xkcd.com/1209/
>>
>> --
>>
>>
>> This reflects a lack of understanding of Unicode.
>>
>> jmf
>
>
> And this reflects a lack of a sense of humor.  :)

Isn't that a crime in the UK?

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


Re: object.enable() anti-pattern

2013-05-10 Thread Chris Angelico
On Sat, May 11, 2013 at 1:21 AM, Roy Smith  wrote:
> In article ,
>  Chris Angelico  wrote:
>>
>> Agreed, in generality. But what is actually gained by hiding data from
>> yourself?
>
> You're not hiding it from yourself.  You're hiding it from the other
> people who are using your code and may not understand all the subtle
> gotchas as well as you do.

True. And on looking over my code, I find that there are a few cases
where I've used private members: I have a buffer class that acts
pretty much like a non-refcounted string, and it declares a private
copy constructor to prevent accidental misuse. But it's the exception,
not the rule. My main point isn't about the cases where you actually
want to prevent access, but the all-too-common case where the member
itself is private and there are two public methods to get and set it.
Massive boilerplate. Completely unnecessary in 99%+ of cases.

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


Re: object.enable() anti-pattern

2013-05-10 Thread Chris Angelico
On Sat, May 11, 2013 at 1:44 AM, Serhiy Storchaka  wrote:
> 10.05.13 15:19, Robert Kern написав(ла):
>
>> I'd be curious to see in-the-wild instances of the anti-pattern that you
>> are talking about, then.
>
>
> Many (if not most) GUI frameworks use this pattern.
>
> button = Button("text")
> button.setForegroundColor(...)
> button.setBackgoundColor(...)
> button.setFont(...)
> button.setRelief(...)
> button.setBorder(...)
> button.setWidth(...)
> button.setAction(...)
> button.setMouseListener(...)
> button.place(...)

The button really exists, though. You could merge the creation and
placement (or in the case of a window/dialog, the creation and
showing), but it's often useful to not. However, in the specific case
you have there, there's an alternative: a mapping of attributes and
values passed to the constructor, and then you could pass the
constructed object directly to a place(). That would let you, if you
wished, effectively construct a Button with a parent right there,
which makes reasonable sense.

> Another example is running a subprocess in Unix-like systems.
>
> fork()
> open/close file descriptors, set limits, etc
> exec*()

Hrm. Not really a corresponding example. After you fork, you have two
actual processes. Following up with an exec is only one of the
possible options; I've done code that forks and execs, and code that
forks and keeps running, and neither of them feels "wrong" in any way.
There IS a function that's similar to what you're saying, and that's
vfork:

"""
(From POSIX.1) The vfork() function has the same effect as fork(2),
except that the behavior is undefined if the process created by
vfork() either modifies any data other than a variable of type pid_t
used to store the return value from vfork(), or returns from the
function in which vfork() was called, or calls any other function
before successfully calling _exit(2) or one of the exec(3) family of
functions.
"""

It's deprecated because it's so fragile (and because regular fork()
isn't that much less efficient now; AIUI, vfork was meant to be a
lightweight fork). I would say that the deprecation of vfork in favour
of fork is a strong indication that the object.enable() anti-pattern
can come up in kernel APIs too, and isn't liked there either.

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


Re: Unicode humor

2013-05-11 Thread Chris Angelico
On Sat, May 11, 2013 at 2:07 AM, rusi  wrote:
> On May 10, 8:32 pm, Chris Angelico  wrote:
>> On Sat, May 11, 2013 at 1:24 AM, Ned Batchelder  
>> wrote:
>> > On 5/10/2013 11:06 AM, jmfauth wrote:
>>
>> >> On 8 mai, 15:19, Roy Smith  wrote:
>>
>> >>> Apropos to any of the myriad unicode threads that have been going on
>> >>> recently:
>>
>> >>>http://xkcd.com/1209/
>>
>> >> --
>>
>> >> This reflects a lack of understanding of Unicode.
>>
>> >> jmf
>>
>> > And this reflects a lack of a sense of humor.  :)
>>
>> Isn't that a crime in the UK?
>>
>> ChrisA
>
> The problem with English humour (as against standard humor) is that
> its not unicode compliant

Unicode humour was carefully laid out to incorporate English humour.
In fact, if you use the standard variable-length-joke encoding, it's
possible for a Unicode joke to be decoded as if it were an English
joke, without any actual knowledge of Unicode. Unfortunately, this can
result in non-compliant English humour publishers producing jokes that
come out as gibberish in the rest of the world. Fortunately, we then
get to laugh at them.

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


Re: Making safe file names

2013-05-11 Thread Chris Angelico
On Thu, May 9, 2013 at 1:08 PM, Steven D'Aprano
 wrote:
> I suspect that the only way to be completely ungoogleable would be to
> name yourself something common, not something obscure. Say, if you called
> yourself "Hard Rock Band", and did hard rock. But then, googling for
> "Heavy Metal" alone brings up the magazine as the fourth hit, so if you
> get famous enough, even that won't work.

Yeah, so why are ubergeneric domain names worth so much? Whatevs.

The best way to be findable in a web search is to have content on your
web site. Real crawlable content. I guarantee you'll be found. Even if
you're some tiny thing tucked away in a corner of teh interwebs, you
can be found.

http://www.google.com/search?q=minstrel+hall

The song is there, but so is an obscure little D&D MUD.

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


Re: Append to python List

2013-05-11 Thread Chris Angelico
On Thu, May 9, 2013 at 9:30 PM, Jussi Piitulainen
 wrote:
> 8 Dihedral writes:
>
>> This is just the handy style for a non-critical loop.
>> In a critical loop, the number of  the total operation counts
>> does matter in the execution speed.
>
> Do you use speed often?

Dihedral is a bot. Quite a good one, but a bot.

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


Re: Message passing syntax for objects | OOPv2

2013-05-11 Thread Chris Angelico
On Fri, May 10, 2013 at 3:33 AM, Ian Kelly  wrote:
> All this irrelevant nonsense
> about Turing machines and lambda calculus that you've injected into
> the conversation though just reminds me of the "Einstein was wrong"
> cranks.

http://xkcd.com/1206/

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


Re: Unicode humor

2013-05-11 Thread Chris Angelico
On Sat, May 11, 2013 at 10:40 PM, Mark Lawrence  wrote:
> This simply shows bias to the English speaking world, as does Python
> unicode, at least in 3.3+.  I wouldn't mind betting that other languages
> can't cope, e.g. can 3.3+ manage the top secret joke that's so deadly even
> the Germans die laughing?

It most certainly can. However, the space it takes up depends on how
you encode the combining characters; for maximal efficiency of
transmission, you would want to use the fully-composed version,
because like music, if it isn't composed, it's decomposed.

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


Re: Append to python List

2013-05-11 Thread Chris Angelico
On Sun, May 12, 2013 at 1:47 AM, Anssi Saari  wrote:
> Chris Angelico  writes:
>
>> On Thu, May 9, 2013 at 9:30 PM, Jussi Piitulainen
>>  wrote:
>>> 8 Dihedral writes:
>>>
>>>> This is just the handy style for a non-critical loop.
>>>> In a critical loop, the number of  the total operation counts
>>>> does matter in the execution speed.
>>>
>>> Do you use speed often?
>>
>> Dihedral is a bot. Quite a good one, but a bot.
>
> That's been said often enough. Is the source available and is it in
> Python?

Not to my knowledge. Technically Dihedral is merely _rumoured_ to be a
bot, as we have no actual proof; but we've been conducting a variety
of Turing tests via this list and have yet to see any strong argument
for his being deemed human. Most humans would get defensive, or at
least protest, if treated as bots; Dihedral never has, despite being
referred to in this way a number of times.

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


Re: object.enable() anti-pattern

2013-05-11 Thread Chris Angelico
On Sun, May 12, 2013 at 1:33 AM, André Malo  wrote:
> * Serhiy Storchaka wrote:
>
>> Another example is running a subprocess in Unix-like systems.
>>
>>  fork()
>>  open/close file descriptors, set limits, etc
>>  exec*()
>
> For running a subprocess, only fork() is needed. For starting another
> executable, only exec() is needed. For running the new executable in a
> subprocess fork() and exec() are needed. I think, that's a bad example.
> These APIs are actually well-designed.

That said, though, there's certainly plenty of room for one-call APIs
like popen. For the simple case where you want to start a process with
some other executable, wait for it to finish, and then work with its
return value, it makes sense to hide the details of fork/exec/wait -
especially since that simple API can be cross-platform, where fork()
itself is quite hard to implement on Windows.

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


Re: object.enable() anti-pattern

2013-05-11 Thread Chris Angelico
On Sun, May 12, 2013 at 5:55 AM, Robert Kern  wrote:
>> Another example of temporal coupling is json_decode in PHP: you must
>> follow it by a call to json_last_error, otherwise you have no way of
>> telling whether the json_decode function succeeded or not.
>>
>> http://php.net/manual/en/function.json-last-error.php
>
>
> I suspect that the author might say something about error checking being
> optional. But yeah, terrible API. :-)

The problem with that one isn't that error checking is optional, but
that errors are signalled with a perfectly legal return value (FALSE,
if I recall correctly - which is also returned if you json_decode a
boolean false). Better design would either throw an exception on
error, or have a unique sentinel representing the errorness of the
return value.

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


Re: Message passing syntax for objects | OOPv2

2013-05-11 Thread Chris Angelico
On Sun, May 12, 2013 at 5:32 AM, Dennis Lee Bieber
 wrote:
> On Fri, 10 May 2013 14:33:52 +1000, Chris Angelico 
> declaimed the following in gmane.comp.python.general:
>
>>
>> I don't answer to them. I also believe in a path of endless
>> exponential growth. Challenge: Create more information than can be
>> stored in one teaspoon of matter. Go ahead. Try!
>>
> The coordinates of each particle storing the information in that
> teaspoon of matter.

Which is probably more data than any of us will keyboard in a
lifetime. Hence my point.

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


Re: Message passing syntax for objects | OOPv2

2013-05-11 Thread Chris Angelico
On Sun, May 12, 2013 at 10:50 AM, Gregory Ewing
 wrote:
> Dennis Lee Bieber wrote:
>>>
>>> I also believe in a path of endless
>>> exponential growth. Challenge: Create more information than can be
>>> stored in one teaspoon of matter. Go ahead. Try!
>
>
> If that's your argument, then you don't really believe
> in *endless* exponential growth. You only believe in
> "exponential growth for long enough that I won't be
> around to suffer the consequences when it runs out".

Technically, according to the laws of thermodynamics, there cannot be
any actually endless growth, yes. (Anything beyond that is the realm
of religion, not science.) But in that case, the term "endless" is
like "infinity" - a concept only. Like the Infinite Monkey Protocol
Suite description in RFC 2795, there will be many numbers that come up
that are plenty huge but fall pitifully short of infinity (Graham's
Number, for instance, is pretty small in those terms).

So long as storage capacities keep on increasing, we can keep
increasing the world's information at the same rate. So long as the
number of computers connected to the internet increases, we can keep
increasing the internet's information at the same rate. Put both
together - and neither shows any sign of ceasing any time soon - we
can continue with the corresponding growth. How long before that runs
out? A *long* time. We're not talking here of the Year 2000, a
couple of decades after the software was written. We're not talking
about the 2038 issues, roughly half a century after the software was
written. We are talking timeframes that make the Y10K problem look
like a serious lack of foresight.

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


Re: Message passing syntax for objects | OOPv2

2013-05-11 Thread Chris Angelico
On Sun, May 12, 2013 at 11:02 AM, Gregory Ewing
 wrote:
> Chris Angelico wrote:
>>
>> On Sun, May 12, 2013 at 5:32 AM, Dennis Lee Bieber
>>  wrote:
>
>
>>>The coordinates of each particle storing the information in that
>>> teaspoon of matter.
>>
>>
>> Which is probably more data than any of us will keyboard in a
>> lifetime. Hence my point.
>
>
> My 1TB hard disk *already* contains more information than
> I could keyboard in my lifetime.
>
> The fact that it all got there is due to two things: (1)
> I didn't have to enter it all myself, and (2) most of it
> was auto-generated from other information, using compilers
> and other such tools.

I would like to differentiate between information and data, here.
Point 1 is correct, but point 2 is not; auto-generated data is not
more information, and basic data compression can improve that. (Simple
form of compression there: `rm *.o` - you've lost nothing.)

> Our disk capacities are increasing exponentially, but
> so is the rate at which we have the ability to create
> information. I wouldn't be surprised if, at some point
> before the human race becomes extinct, we build
> computers whose operating system requires more than
> a teaspoonful of atoms to store. Especially if
> Microsoft still exists by then. :-)

That's possible. But that would be data bloat, not true information.
It's certainly possible to conceive more data than can be stored.
Microsoft, as you cite, are experts at this :)

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


Re: Append to python List

2013-05-11 Thread Chris Angelico
On Sun, May 12, 2013 at 12:29 PM, 8 Dihedral
 wrote:
> Chris Angelico於 2013年5月12日星期日UTC+8上午12時00分44秒寫道:
>> Most humans would get defensive, or at
>> least protest, if treated as bots; Dihedral never has, despite being
>> referred to in this way a number of times.
>>
>> ChrisA
>
> Don't you get the practices of   POSIX ?

I rest my case, m'lud.

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


Re: Python for philosophers

2013-05-11 Thread Chris Angelico
On Sun, May 12, 2013 at 2:22 PM, rusi  wrote:
> On May 12, 3:16 am, alex23  wrote:
>> On 12 May, 06:10, Mark Janssen  wrote:
>>
>> > Wow.  You must be from another planet.  Find Socrates if you wish to
>> > know these things.  He's from there also.
>>
>> Now now, there's no need for a turf war, there's plenty of room on
>> this list for crazies.
>
> I'm reminded of this:
>
> Conversation between inmate and attendant in an asylum
>
> Inmate: I am Napoleon
> Attendant: Yes of course. But how did you know that?
> Inmate: God himself told me s…
> [Loud voice from another corner] I told you no such thing!

Who's been telling you of private conversations between Steven and me?

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


Old version docs don't link to current version

2013-05-12 Thread Chris Angelico
Not sure if this is an oversight or something deliberate... could be either.

>From http://docs.python.org/3.0/library/http.server.html there's no
link to the current docs, even though from
http://docs.python.org/3/library/http.server.html it's possible to
switch to 3.2 and then back to 3.3 (or to 2.7, but that fails and
redirects since http.server doesn't exist in 2.7). This wouldn't be
much of a bother, except that a Google search for 'python http.server'
(which is the way I normally pull up Python docs) landed me on /3.0/
instead of /3/.

Was this intentional, along the lines of not touching the old and
unsupported docs?

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


Re: Python for philosophers

2013-05-12 Thread Chris Angelico
On Mon, May 13, 2013 at 12:17 AM, Citizen Kant  wrote:
> Maybe It'd be good if I explain myself a bit more. What I'm trying here is
> to grasp Python from the game's abstraction point of view, as if it were,
> for example, chess.

Maybe you're going for something a little too complicated. Let's boil
the question down to a much MUCH simpler subset: expression
evaluation. And let's take Python itself right out of the picture, and
work with only the following elements:

* Parentheses ( )
* Multiplication and division * /
* Addition and subtraction + -
* Decimal integer constants 0123456789

This will give the basics of algebraic evaluation. It's quite fun to
build a simple little expression evaluator that just does these few
operations, and it's surprisingly useful (embed it within a command
interpreter, for instance). Some time ago I wrote one into a Windows
app (written in C++), and when I pulled it out just now and made it a
stand-alone tool, the whole thing was only ~60 lines of code. Nice and
easy to work with.

So, let's take an expression and see what it really means.

2*(3+4)+6

One way to interpret this is with a stack. Here's how Python evaluates
that expression:

>>> def foo():
return 2*(three+4)+6

>>> dis.dis(foo)
  2   0 LOAD_CONST   1 (2)
  3 LOAD_GLOBAL  0 (three)
  6 LOAD_CONST   2 (4)
  9 BINARY_ADD
 10 BINARY_MULTIPLY
 11 LOAD_CONST   3 (6)
 14 BINARY_ADD
 15 RETURN_VALUE

(I had to replace one of the constants with a global, to foil the optimizer)

The LOAD statements add to an internal stack, the BINARY operations
pop two operands and push the result. This is more-or-less the same
technique as I used in my evaluator, except that instead of compiling
it to code, I just march straight through, left to right, and so I had
to maintain two stacks (one of operands, one of operators).

Is this what you had in mind when you wanted to grasp Python's
internals? Because it's pretty easy to explore, thanks to the dis
module. There's a huge amount that can be learned about the
interpreter, its optimizers, and so on, just by disassembling
functions. Alternatively, if you're thinking on a more abstract level,
leave Python aside altogether and pick up a book on language design.
Also can be awesome fun, but completely different.

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


Re: in need of some help...

2013-05-12 Thread Chris Angelico
On Mon, May 13, 2013 at 1:59 AM, Chris “Kwpolska” Warrick
 wrote:
> On Sun, May 12, 2013 at 12:20 AM, Jens Thoms Toerring  
> wrote:
>> PS: If I may ask you a favor: consider refraining from using Google's
>> completely broken interface to newsgroups - your post consists
>> of nearly 200 lines of text containing all I wrote, with an empty
>> line inserted between each of them, and a single line of text
>> you wrote. It's rather annoying to have to sieve through that
>> much of unrelated stuff just to find thar one line that's re-
>> levant.
>
> Gmail automatically hides long quotes.  This is helpful in situations
> like this one.  More mail software should implement that
> functionality.  Seriously: once you go Gmail, you never go back.

I use Gmail, but the automated hiding of long quotes is *disrupted* by
the double-spacing. So it's no less important to avoid breaking
protocol.

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


Re: Python for philosophers

2013-05-12 Thread Chris Angelico
On Mon, May 13, 2013 at 4:13 AM, llanitedave  wrote:
> On Sunday, May 12, 2013 7:51:28 AM UTC-7, Chris Angelico wrote:
>> On Mon, May 13, 2013 at 12:17 AM, Citizen Kant  wrote:
>>
>> > Maybe It'd be good if I explain myself a bit more. What I'm trying here is
>>
>> > to grasp Python from the game's abstraction point of view, as if it were,
>>
>> > for example, chess.
>>
>>
>>
>> Maybe you're going for something a little too complicated. Let's boil
>>
>> the question down to a much MUCH simpler subset: expression
>>
>> evaluation. And let's take Python itself right out of the picture, and
>>
>> work with only the following elements:
>>
>>
>>
>> * Parentheses ( )
>>
>> * Multiplication and division * /
>>
>> * Addition and subtraction + -
>>
>> * Decimal integer constants 0123456789
>>
>>
>>
>> This will give the basics of algebraic evaluation. It's quite fun to
>>
>> build a simple little expression evaluator that just does these few
>>
>> operations, and it's surprisingly useful (embed it within a command
>>
>> interpreter, for instance). Some time ago I wrote one into a Windows
>>
>> app (written in C++), and when I pulled it out just now and made it a
>>
>> stand-alone tool, the whole thing was only ~60 lines of code. Nice and
>>
>> easy to work with.
>>
>>
>>
>> So, let's take an expression and see what it really means.
>>
>>
>>
>> 2*(3+4)+6
>>
>>
>>
>> One way to interpret this is with a stack. Here's how Python evaluates
>>
>> that expression:
>>
>>
>>
>> >>> def foo():
>>
>>   return 2*(three+4)+6
>>
>>
>>
>> >>> dis.dis(foo)
>>
>>   2   0 LOAD_CONST   1 (2)
>>
>>   3 LOAD_GLOBAL  0 (three)
>>
>>   6 LOAD_CONST   2 (4)
>>
>>   9 BINARY_ADD
>>
>>  10 BINARY_MULTIPLY
>>
>>  11 LOAD_CONST   3 (6)
>>
>>  14 BINARY_ADD
>>
>>  15 RETURN_VALUE
>>
>>
>>
>> (I had to replace one of the constants with a global, to foil the optimizer)
>>
>>
>>
>> The LOAD statements add to an internal stack, the BINARY operations
>>
>> pop two operands and push the result. This is more-or-less the same
>>
>> technique as I used in my evaluator, except that instead of compiling
>>
>> it to code, I just march straight through, left to right, and so I had
>>
>> to maintain two stacks (one of operands, one of operators).
>>
>>
>>
>> Is this what you had in mind when you wanted to grasp Python's
>>
>> internals? Because it's pretty easy to explore, thanks to the dis
>>
>> module. There's a huge amount that can be learned about the
>>
>> interpreter, its optimizers, and so on, just by disassembling
>>
>> functions. Alternatively, if you're thinking on a more abstract level,
>>
>> leave Python aside altogether and pick up a book on language design.
>>
>> Also can be awesome fun, but completely different.
>>
>>
>>
>> ChrisA
>
> No, that won't help.  You're trying to give him knowledge; he wants 
> understanding.

I can't give him understanding. Best I can do is offer facts, which
lead to knowledge, which lead to understanding if absorbed
appropriately. Also, sources of knowledge (like dis.dis) can be VERY
powerful tools in gaining understanding.

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


Re: Old version docs don't link to current version

2013-05-12 Thread Chris Angelico
On Mon, May 13, 2013 at 5:32 AM, Terry Jan Reedy  wrote:
> On 5/12/2013 10:12 AM, Chris Angelico wrote:
>>
>> Was this intentional, along the lines of not touching the old and
>> unsupported docs?
>
> Cross referencing was added while 3.2 docs were still subject to revision.
> x.y docs are essentially frozen once the final x.y.z bugfix comes out.

So, yeah, not touching the old docs. Okay!

It's not a particularly big deal, I can just delete a couple of
characters out of the URL. But it'd be nice if people who link to the
docs could start doing so using /3/ so that we have a chance of
getting past this eventually.

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


Re: in need of some help...

2013-05-12 Thread Chris Angelico
On Mon, May 13, 2013 at 7:56 AM, Jens Thoms Toerring  wrote:
> Chris “Kwpolska” Warrick  wrote:
>> Gmail automatically hides long quotes.  This is helpful in situations
>> like this one.  More mail software should implement that
>> functionality.  Seriously: once you go Gmail, you never go back.
>
> i giess you mean Gougle groups and not Gmail, which I can't comment
> on since I don't use it.
>

No, Chris (not me, the other Chris... *an*other Chris okay, one of
the chorus of Chrises of this list!) did mean Gmail, the Google
webmail client. It does threading (and does it better than
SquirrelMail does), and it does the hiding of long quotes, long
signatures, etc.

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


Re: in need of some help...

2013-05-12 Thread Chris Angelico
On Mon, May 13, 2013 at 8:58 AM, Jens Thoms Toerring  wrote:
> Chris Angelico  wrote:
>> On Mon, May 13, 2013 at 7:56 AM, Jens Thoms Toerring  
>> wrote:
>> > Chris “Kwpolska” Warrick  wrote:
>> >> Gmail automatically hides long quotes.  This is helpful in situations
>> >> like this one.  More mail software should implement that
>> >> functionality.  Seriously: once you go Gmail, you never go back.
>> >
>> > i giess you mean Gougle groups and not Gmail, which I can't comment
>> > on since I don't use it.
>
>> No, Chris (not me, the other Chris... *an*other Chris okay, one of
>> the chorus of Chrises of this list!) did mean Gmail, the Google
>> webmail client. It does threading (and does it better than
>> SquirrelMail does), and it does the hiding of long quotes, long
>> signatures, etc.
>
> Ok, sorry then about that - as I said I never have used Gmail
> (and don't plan using it for other reasons than usability - and
> then I would hardly consider anything with a web interface for a
> text medium to be very usable;-). But, as far as I understand,
> Gmail is about email, so I'm a bit at a loss to understand what
> got this to do with news groups and Google groups (were the post
> I originally was responing to according to the header seemed to
> be coming from) that I intended this to be about?

Since you can subscribe to the mailing list python-list@python.org and
get all of comp.lang.python (sans a pile of spam), you can read it as
a threaded mailing list instead of a newsgroup. It comes to pretty
much the same thing, so effectively you get your choice of technology.

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


Re: in need of some help...

2013-05-12 Thread Chris Angelico
On Mon, May 13, 2013 at 9:47 AM, Dennis Lee Bieber
 wrote:
> On Mon, 13 May 2013 08:18:05 +1000, Chris Angelico 
> declaimed the following in gmane.comp.python.general:
>
>>
>> No, Chris (not me, the other Chris... *an*other Chris okay, one of
>> the chorus of Chrises of this list!) did mean Gmail, the Google
>
> Is that the accepted group noun? I'd think a "crisis of Chrises" is
> more alliterative...

That works too! I automatically went for "chorus" since I work in
theatre, but I like your version. What do the other Chrises think?

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


Re: object.enable() anti-pattern

2013-05-13 Thread Chris Angelico
On Mon, May 13, 2013 at 4:32 PM, Fábio Santos  wrote:
>
> On 13 May 2013 00:22, "Greg Ewing"  wrote:
>> The same argument can be applied to:
>>
>>foo = Foo()
>>foo.do_something()
>>foo.enable() # should have done this first
>>
>> You're passing an invalid input to Foo.do_something,
>> namely a Foo that hasn't been enabled yet.
>
> I don't think you can really count that as invalid input in OOP terms. After
> all in most languages `self` / `this` / whatever is not an argument to every
> method.

Yes, it is; it's just often implicit. C++ lets you poke around with
the internals, and it's pretty clear that 'this' is an argument. (See
for instance what happens with the gcc 'format' attribute - I can't
find a convenient docs page, but it's been mentioned on SO [1] and can
be easily verified.) EMCAScript lets you call any function with any
'this' by using the .call() or .apply() methods - which, in my
extremely not-humble opinionated opinion, is bad design (closures work
implicitly, but the 'this' pointer doesn't??). Python turns an
attribute lookup on an instance into an attribute lookup on the class
plus a currying. One way or another, the bit-before-the-dot is an
argument to the function.

[1] 
http://stackoverflow.com/questions/11621043/how-should-i-properly-use-attribute-format-printf-x-y-inside-a-class

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


Re: Python for philosophers

2013-05-13 Thread Chris Angelico
On Tue, May 14, 2013 at 12:53 AM, rusi  wrote:
> int fact(int n, int acc)
> {
>   return !n? acc : fact(n-1,acc*n);
> }
> -
> When I run these, the C happily keeps giving answers until a million
>
> However examined closely we find that though the C is giving answers
> its giving junk after around 12
> fact 17 is -288522240
> And 35 onwards its 0 (!!)

That'll depend on your integer size. If it's a 32-bit integer, you
can't store numbers greater than 2**31-1 (if you declared it as
'unsigned int', you could go all the way to 2**32-1). I'm sure you
could write this to use the GNU Multi-Precision library, but it'd be a
lot more complicated. However, as far as I know, the Turing machine
never promises that; its cells aren't meant to be infinite integers.

The Python script is, of course, governed by sys.setrecursionlimit().
But by adding a simple driver, we can test the real limit:

import sys

def fact(n,acc=1):
return acc if not n else fact(n-1,n*acc)

n=2
while True:
sys.setrecursionlimit(n+2)
print("fact",n,"has",len(str(fact(n))),"digits")
n*=2

On my 64-bit system, running a recent trunk build of CPython 3.4, it
can calculate 8192! but not 16384! (segfault). The limit seems to be
12772; after that, boom. Your crash-point will quite probably vary,
and I'd say there'll be compile-time options that would change that.

Of course, after playing with this in Python, I had to try out Pike.
Using the exact same code you proposed for C, but with a different
main() to save me the hassle of keying in numbers manually, I get
this:

fact 8192 has 28504 digits - 0.026 secs
fact 16384 has 61937 digits - 0.097 secs
fact 32768 has 133734 digits - 0.389 secs
fact 65536 has 287194 digits - 1.628 secs
fact 131072 has 613842 digits - 7.114 secs
fact 262144 has 1306594 digits - 31.291 secs
fact 524288 has 2771010 digits - 133.146 secs

It's still going. One core consumed, happily working on 1048576!, and
not actually using all that much memory. Hmm looks like the Pike
optimizer has turned this non-recursive. Okay, let's tweak it so it's
not tail-recursion-optimizable:

  return n?n*fact(n-1,1):1;

Now it bombs at 65536, saying:

Svalue stack overflow. (99624 of 10 entries on stack, needed 256
more entries)

Hey, it's better than a segfault, which is what C would have done :)
And it's a tweakable value, though I don't know what the consequences
are of increasing it (presumably increased RAM usage for all Pike
programs).

Your final conclusion is of course correct; nothing we build can be
truly infinite. But we can certainly give some very good
approximations, if we're prepared to pay for them. The reality is,
though, that we usually do not want to pay for approximations to
infinity; why is IEEE 754 floating point so much more used than, say,
arbitrary-precision rational? Most of the time, we'd rather have good
performance and adequate accuracy than abysmal performance and perfect
accuracy. But hey, if you want to render a Mandelbrot set and zoom in
to infinity, the option IS there.

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


Re: Python's sad, unimaginative Enum

2013-05-13 Thread Chris Angelico
On Mon, May 13, 2013 at 8:17 PM, Steven D'Aprano
 wrote:
> Let's look at his major criticisms:
>
> 1) values aren't automatically generated.
>
> True. So what? That is the *least* important part of enums.

I stopped following the -ideas threads about enums, but IIRC
autogeneration of values was in quite a few of the specs early on. So
you can probably find the arguments against it in the list archives.

FWIW, though, I do like C's autogeneration of enum values - but use it
in only a small proportion of my enums. It's not a terrible loss, but
it is a loss.

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


Re: [Off topic] Software epigrams

2013-05-13 Thread Chris Angelico
On Mon, May 13, 2013 at 7:20 PM, Steven D'Aprano
 wrote:
> My, it's been a long time since I've seen these:
>
> http://pu.inf.uni-tuebingen.de/users/klaeren/epigrams.html
>
> They pre-date the Zen of Python by at least a decade, and quite frankly I
> think many of them miss the mark. But whether you agree or disagree with
> them, they're worth reading.

8. A programming language is low level when its programs require
attention to the irrelevant.

So much a matter of debate. Indentation is irrelevant, why should
Python programs pay attention to it? Block delimiters are irrelevant
too, the interpreter should be able to figure them out from the code
layout. But this one is absolutely right:

16. Every program has (at least) two purposes: the one for which it
was written and another for which it wasn't.

48. The best book on programming for the layman is "Alice in
Wonderland"; but that's because it's the best book on anything for the
layman.

LGTM.

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


Re: [Off topic] Software epigrams

2013-05-13 Thread Chris Angelico
On Tue, May 14, 2013 at 4:02 AM, Skip Montanaro  wrote:
>> 8. A programming language is low level when its programs require
>> attention to the irrelevant.
>>
>> So much a matter of debate. Indentation is irrelevant, why should
>> Python programs pay attention to it? Block delimiters are irrelevant
>> too, the interpreter should be able to figure them out from the code
>> layout. But this one is absolutely right:
>
> I think "irrelevant" in this context means stuff like memory management.

Sure. That one's pretty clear (if you care about memory management,
you want a low level language). But there's still plenty that are less
clear. Though in generalities, I think I agree; paying attention to
minutiae is the consequence of taking a lower-level language. It's
just that the difference between relevant and irrelevant is hard to
define.

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


Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]

2013-05-13 Thread Chris Angelico
On Tue, May 14, 2013 at 4:08 AM, Ned Batchelder  wrote:
>
> On 5/13/2013 1:26 PM, Fábio Santos wrote:
>
>
> On 13 May 2013 11:04, "Alister"  wrote:
>> this looks to me like an issue with operator precidence
>>
>> you code is evaluating as (Not x) == y
>> rather than not (x == y)
>
> I can say for sure that the precedence is as expected. I always use "not ...
> == ..." Instead of !=.
>
>
>
> If you don't mind my asking, why do you do that?

I think it's fairly obvious. Like the stumpy-tailed dog from "The
Loaded Dog" [1], he's saving up the != operator in case he needs it
later.

ChrisA

[1] Full text here. http://jendi.bowmeow.com.au/loadeddog1.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Off topic] Software epigrams

2013-05-13 Thread Chris Angelico
On Tue, May 14, 2013 at 1:08 PM, Dan Sommers  wrote:
> And if I've designed my program the right way, what's relevant in one
> place (package, module, function, line of code) is different from what's
> relevant in another.

Absolutely. Layered systems FTW! Nothing matters but your current
layer and those it touches.

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


Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]

2013-05-14 Thread Chris Angelico
On Tue, May 14, 2013 at 9:22 AM, Dave Angel  wrote:
> On 05/13/2013 06:53 PM, Mark Lawrence wrote:
>> I much prefer the alternative <> for != but some silly people insisted
>> that this be removed from Python3.  Just how stupid can you get?
>>
>
> So which special methods should the <> operator call?  By rights it ought to
> call both __gt__ and __lt__ and return True if either of them is True.

Why do you think that? After all, the != operator doesn't call
__factorial__ and __assignment__ and return True if either is True,
does it?

ChrisA

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


Re: Writing a blog post on the new Enum.

2013-05-14 Thread Chris Angelico
On Tue, May 14, 2013 at 9:40 AM, Fábio Santos  wrote:
> Well I am thus defying the law and order of this world by publishing
> it on the internets!
>
> ---
>
> And here it is:
> http://fabiosantoscode.blogspot.pt/2013/05/pythons-new-enum-class.html

class Text(unicode, Enum):
one = u'one'
two = u'two'
three = u'three'

That looks like Python 2 code. Are you backporting Enum to Py2
manually? AIUI the Python core won't be adding features like that to
2.7, and there won't be a 2.8, so PEP 435 will be Py3.4+ only. Or have
I misunderstood it?

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


Re: Writing a blog post on the new Enum.

2013-05-14 Thread Chris Angelico
On Wed, May 15, 2013 at 1:07 AM, Terry Jan Reedy  wrote:
> On 5/14/2013 3:52 AM, Chris Angelico wrote:
>>
>> On Tue, May 14, 2013 at 9:40 AM, Fábio Santos 
>> wrote:
>
>>> http://fabiosantoscode.blogspot.pt/2013/05/pythons-new-enum-class.html
>>
>>
>>  class Text(unicode, Enum):
>>  one = u'one'
>>  two = u'two'
>>  three = u'three'
>
>
> Is this supposed to be a quote? or your rewrite? or did Santos rewrite after
> you posted? The blog currently has a 3.x version of that.

It was a quote from the blog post as it had been when I posted it.
Presumably he edited the post subsequently, as I'm now seeing the same
thing you are, a 3.x-compat version. (The u'xx' prefixes wouldn't be a
problem, incidentally, so this could be dual-versionned just by going
"unicode = str".)

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


Re: Python for philosophers

2013-05-15 Thread Chris Angelico
On Tue, May 14, 2013 at 4:14 AM, rusi  wrote:
> It costs $10K for a car which goes at around 80 kmph
>
> Now if I want to move at 800 kmph I need to switch from car to plane
> and that will cost me in millions
>
> And if I want to move at 8000 kmph I need to be in a rocket in outer
> space. Cost perhaps in billions
>
> And maybe if I spend in trillions (leaving aside the question where I
> got the trillions) maybe my rocket can go at 80,000 kmph
>
> So what will it cost me to have a rocket that will go at 300,000 m/sec
> (186,000 miles per second may be more familiar)?

A $1 pocket flashlight.

:)

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


Re: Translation API in Python

2013-05-15 Thread Chris Angelico
On Thu, May 16, 2013 at 8:00 AM, Hala Gamal  wrote:
> I want to use A translator from Arabic to English and reverse in my 
> application which is written in pyhton,
> Is there  any open source Translator that can be used with python,
> Or Any Suggestion?
> Please Help,
> Thanks In Advance :)

I would recommend, in order:
1) Searching the Python modules [1]
2) Searching PyPI [2]
3) Searching the web [3]
4) Finding a translation program that uses stdin/stdout

I suspect #1 will come up blank, but any of the others could well come
up with something. Working with an external program is a bit harder
than an actual Python module, but it'll work.

ChrisA
[1] http://docs.python.org/3/
[2] https://pypi.python.org/pypi
[3] http://www.google.com/ or http://www.duckduckgo.com/ or
http://yahoo.com/ or whatever
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fractal

2013-05-16 Thread Chris Angelico
On Thu, May 16, 2013 at 5:11 PM, Ulrich Eckhardt
 wrote:
> Am 16.05.2013 02:00, schrieb alex23:
>
>> My favourite is this one:
>>
>> http://preshing.com/20110926/high-resolution-mandelbrot-in-obfuscated-python
>
>
> Not only is this blog entry an interesting piece of art, there's other
> interesting things to read there, too.

I'm quite impressed, actually. Most people don't use Python for code
art. Significant indentation is not usually a good thing there :)

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


Re: Fwd: Fwd: Fwd: Python for philosophers

2013-05-16 Thread Chris Angelico
On Thu, May 16, 2013 at 11:46 PM, rusi  wrote:
> IOW a programmer is one who quickly and easily comes to the nub/core/
> kernel/essence of a problem and as easily and adroitly shaves off the
> irrelevant.

+1.

This is a fairly good description of a programmer's job. Of course,
that's the theoretical and pure programmer... a professional
programmer often has to:

* Figure out what the problem *is* based on an incomplet description
from an incompetent user via a bored telephone operator

* Traverse a morass of bureaucratic requirements and politicking just
to get the necessary hardware/software to do his work

* Deal with the Layer Eight firewalling against the implementation of
the solution he comes up with

* Attend inane meetings with bikeshedding non-technical people who
have some kind of authority over the project

* Etcetera, etcetera, etcetera.

But yeah, that's what a programmer is. :)

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


Re: [Off topic] Software epigrams

2013-05-16 Thread Chris Angelico
On Fri, May 17, 2013 at 12:23 AM, Neil Cerutti  wrote:
> On 2013-05-16, F?bio Santos  wrote:
>> And in Java we have factories, builders and builderfactories.
>> What's so relevant about them? Java is high level, no?
>
> When I tried to pin down what an irrelevant detail in a computer
> program could be, I couldn't do it. I guess comment decorations,
> maybe? But those would have no bearing on the level of problem
> for which a programming language is most appropriate.

Let me give you a real example.

One of the programs I wrote at work is a simple daemon that runs on
every node in a network. It periodically sends out a heartbeat signal
that the other nodes hear, and if any node hasn't been heard from in X
seconds, it is deemed "down". (It might technically not be down, if
there's a network problem, but the point is that we don't care about
the difference. It's down.) There's also some incidental statussy data
included, for convenience. This is implemented using UDP.

Do I care about how a UDP packet is structured? No.

Do I care about the mechanics of IP routing? No.

Do I care about MAC addresses? No. They might feature in our IPv6
addresses, but I still don't care - the IP addresses (v4 or v6) of the
nodes are treated as opaque tokens.

All I care about is that I call a function with a string of data and a
corresponding function gets called in the other program with that same
string. All the details of how that happens in between aren't
important to my program. They're somewhat of note in the design phase,
but not to the program itself. They are, in fact, irrelevant.

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


Re: Software epigrams

2013-05-16 Thread Chris Angelico
On Fri, May 17, 2013 at 1:06 AM, rusi  wrote:
> On May 16, 7:37 pm, Chris Angelico  wrote:
>> On Fri, May 17, 2013 at 12:23 AM, Neil Cerutti  wrote:
>> > When I tried to pin down what an irrelevant detail in a computer
>> > program could be, I couldn't do it. I guess comment decorations,
>> > maybe? But those would have no bearing on the level of problem
>> > for which a programming language is most appropriate.
>>
>> Let me give you a real example.
>> [snip]
>
> You are just saying (in specific detail) what I said, viz that the
> programmer is one who 'relevates' ie sifts the relevant from the
> irrelevant and a good programming language is one that gives good
> relevating tools:
> http://blog.languager.org/2013/02/c-in-education-and-software-engineering.html

Right. All I'm adding is a concrete example - which, I think, will be
helpful to Neil, and perhaps to others too.

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


Re: spilt question

2013-05-16 Thread Chris Angelico
On Fri, May 17, 2013 at 1:00 AM, loial  wrote:
> I want to split a string so that I always return everything BEFORE the LAST 
> underscore
>
> HELLO_.lst # should return HELLO
> HELLO_GOODBYE_.ls  # should return HELLO_GOODBYE
>
> I have tried with rsplit but cannot get it to work.
>
> Any help appreciated

Try with a limit:

>>> "HELLO_GOODBYE_.ls".rsplit("_",1)
['HELLO_GOODBYE', '.ls']
>>> "HELLO_GOODBYE_.ls".rsplit("_",1)[0]
'HELLO_GOODBYE'

You can easily get docs on it:

>>> help("".rsplit)
Help on built-in function rsplit:

rsplit(...)
S.rsplit(sep=None, maxsplit=-1) -> list of strings

Return a list of the words in S, using sep as the
delimiter string, starting at the end of the string and
working to the front.  If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.

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


Re: any cherypy powred sites I can check out?

2013-05-16 Thread Chris Angelico
On Fri, May 17, 2013 at 4:17 AM,   wrote:
> anyone?
> --
> http://mail.python.org/mailman/listinfo/python-list

You're firing off a bunch of minimal-content threads that ask other
people to do work for you. I recommend you put a bit more thought into
your posts, and show that you're willing to do a basic web search
before you just ask a question :)

Have a read of this:

http://www.catb.org/esr/faqs/smart-questions.html

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


Re: Two Dictionaries and a Sum!

2013-05-17 Thread Chris Angelico
On Sat, May 18, 2013 at 2:19 PM, Bradley Wright
 wrote:
> Confusing subject for a confusing problem (to a novice like me of course!)
> Thx for the help in advance folks
>
> I have (2) dictionaries:
>
> prices = {
> "banana": 4,
> "apple": 2,
> "orange": 1.5,
> "pear": 3
> }
>
> stock = {
> "banana": 6,
> "apple": 0,
> "orange": 32,
> "pear": 15
> }
>
> Here's my instructions:
>
> consider this as an inventory and calculate the sum (thats 4*6 = 24 bananas!)

Let me reword your problem a little, maybe it'll be a bit clearer.
You're trying to calculate the total value of all stock on hand, eg
for insurance purposes. That's not 24 bananas, that's $24 of bananas.
And the part you want now is to get the total value of your entire
stock. Great! You're very close to there...

> HERES MY CODE:
>
> for key in prices:
> print prices[key]*stock[key]
>
> ISSUE:
> I need to find a way to add all of those together...any pointers?

... you just need to accumulate a sum. Since this is almost certainly
homework, I won't give you the answer, but here are a few pointers:

* You'll need a single variable (I use the term sloppily, Python
doesn't actually have variables per se) which will collect the final
total.
* Inside your loop, you're currently printing out an int/float with
the value of the current item. Just add it onto your accumulator.
* Python will happily work with integers and floats together, so you
can just do what's obvious and it'll work.

See where that takes you. Have fun! :)

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


Re: How to write fast into a file in python?

2013-05-17 Thread Chris Angelico
On Sat, May 18, 2013 at 2:01 PM, Steven D'Aprano
 wrote:
> Consider if x is an arbitrary object, and you call "%s" % x:
>
> py> "%s" % 23  # works
> '23'
> py> "%s" % [23, 42]  # works
> '[23, 42]'
>
> and so on for *almost* any object. But if x is a tuple, strange things
> happen

Which can be guarded against by wrapping it up in a tuple. All you're
seeing is that the shortcut notation for a single parameter can't
handle tuples.

>>> def show(x):
return "%s" % (x,)

>>> show(23)
'23'
>>> show((23,))
'(23,)'
>>> show([23,42])
'[23, 42]'

One of the biggest differences between %-formatting and str.format is
that one is an operator and the other a method. The operator is always
going to be faster, but the method can give more flexibility (not that
I've ever needed or wanted to override anything).

>>> def show_format(x):
return "{}".format(x) # Same thing using str.format
>>> dis.dis(show)
  2   0 LOAD_CONST   1 ('%s')
  3 LOAD_FAST0 (x)
  6 BUILD_TUPLE  1
  9 BINARY_MODULO
 10 RETURN_VALUE
>>> dis.dis(show_format)
  2   0 LOAD_CONST   1 ('{}')
  3 LOAD_ATTR0 (format)
  6 LOAD_FAST0 (x)
  9 CALL_FUNCTION1 (1 positional, 0 keyword pair)
 12 RETURN_VALUE

Attribute lookup and function call versus binary operator. Potentially
a lot of flexibility, versus basically hard-coded functionality. But
has anyone ever actually made use of it?

str.format does have some cleaner features, like naming of parameters:

>>> "{foo} vs {bar}".format(foo=1,bar=2)
'1 vs 2'
>>> "%(foo)s vs %(bar)s"%{'foo':1,'bar':2}
'1 vs 2'

Extremely handy when you're working with hugely complex format
strings, and the syntax feels a bit clunky in % (also, it's not
portable to other languages, which is one of %-formatting's biggest
features). Not a huge deal, but if you're doing a lot with that, it
might be a deciding vote.

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


Re: python script is not running

2013-05-18 Thread Chris Angelico
On Sat, May 18, 2013 at 8:12 PM, Avnesh Shakya  wrote:
> avin@hp:~$ crontab -e
> then type -
> */2 * * * * python /home/avin/data/try.py
>

You may need to put an explicit path to your Python interpreter. Type:

$ which python

and put that into your crontab.

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


Re: How to write fast into a file in python?

2013-05-18 Thread Chris Angelico
On Sat, May 18, 2013 at 5:49 PM, Fábio Santos  wrote:
> Putting len(os.linesep)'s value into a local variable will make accessing it
> quite a bit faster. But why would you want to do that?
>
> You mentioned "\n" translating to two lines, but this won't happen. Windows
> will not mess with what you write to your file. It's just that traditionally
> windows and windows programs use \r\n instead of just \n. I think it was for
> compatibility with os/2 or macintosh (I don't remember which), which used \r
> for newlines.
>
> You don't have to follow this convention. If you open a \n-separated file
> with *any* text editor other than notepad, your newlines will be okay.


Into two characters, not two lines, but yes. A file opened in text
mode on Windows will have its lines terminated with two characters.
(And it's old Macs that used to use \r. OS/2 follows the DOS
convention of \r\n, but again, many apps these days are happy with
Unix newlines there too.)

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


Re: python script is not running

2013-05-18 Thread Chris Angelico
On Sun, May 19, 2013 at 3:35 AM, woooee  wrote:
> The obvious question, do you have the shebang on the first line so the
> OS knows it's to be run as a Python program?

That won't make any difference; the cron job specifically stipulates
the interpreter. It just needs to be done with a full path.

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


Re: python script is not running

2013-05-18 Thread Chris Angelico
On Sun, May 19, 2013 at 4:43 AM, Vincent Vande Vyvre
 wrote:
> Le 18/05/2013 19:59, Chris Angelico a écrit :
>
>> On Sun, May 19, 2013 at 3:35 AM, woooee  wrote:
>>>
>>> The obvious question, do you have the shebang on the first line so the
>>> OS knows it's to be run as a Python program?
>>
>> That won't make any difference; the cron job specifically stipulates
>> the interpreter. It just needs to be done with a full path.
>>
>> ChrisA
>
> Not necessary, I use crontab without problem with this line:
>
> 25 16 18 5 * export DISPLAY=:0 & LC_CTYPE="fr_FR.utf-8" Lang="fr_FR.utf-8"
> python /usr/bin/qarte -a 1
>
> ... on Ubuntu.

Everything's configurable. I'd like to hear back from the OP though;
as Roy said, checking 'env' from a cron job will reveal much.

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


Re: Python for philosophers

2013-05-18 Thread Chris Angelico
On Sun, May 19, 2013 at 9:56 AM, 8 Dihedral
 wrote:
> Hey, ChisA, are you delibrately to write a recursive version
> to demonstrate the stack depth problem in Python?
>
> def fact(n):
>ret=1
>if n>1: # integer checking is not used but can be added
>   for x in xrange(n): ret*=x
>#print ret # debugging only for long integers
>return ret
>
>
>
> In a 32 or 64 bit system, this non-recursive verssion
> will be limited by the heap space not by the stack limit.

And just when we're sure Dihedral's a bot, a post like this comes through.

Dihedral, are you intelligent? I'm still in two minds about this...
which may be why you so often appear to have no minds. I dunno.
Mathematics somewhere I fancy.

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


Re: Please help with Threading

2013-05-18 Thread Chris Angelico
On Sun, May 19, 2013 at 10:02 AM, Carlos Nepomuceno
 wrote:
> I didn't know Python threads aren't preemptive. Seems to be something really 
> old considering the state of the art on parallel execution on multi-cores.
>
> What's the catch on making Python threads preemptive? Are there any ongoing 
> projects to make that?

Preemption isn't really the issue here. On the C level, preemptive vs
cooperative usually means the difference between a stalled thread
locking everyone else out and not doing so. Preemption is done at a
lower level than user code (eg the operating system or the CPU),
meaning that user code can't retain control of the CPU.

With interpreted code eg in CPython, it's easy to implement preemption
in the interpreter. I don't know how it's actually done, but one easy
implementation would be "every N bytecode instructions, context
switch". It's still done at a lower level than user code (N bytecode
instructions might all actually be a single tight loop that the
programmer didn't realize was infinite), but it's not at the OS level.

But none of that has anything to do with multiple core usage. The
problem there is that shared data structures need to be accessed
simultaneously, and in CPython, there's a Global Interpreter Lock to
simplify that; but the consequence of the GIL is that no two threads
can simultaneously execute user-level code. There have been
GIL-removal proposals at various times, but the fact remains that a
global lock makes a huge amount of sense and gives pretty good
performance across the board. There's always multiprocessing when you
need multiple CPU-bound threads; it's an explicit way to separate the
shared data (what gets transferred) from local (what doesn't).

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


Re: mutable ints: I think I have painted myself into a corner

2013-05-18 Thread Chris Angelico
On Sun, May 19, 2013 at 10:26 AM, Cameron Simpson  wrote:
> Before I toss this approach and retreat to my former "object"
> technique, does anyone see a way forward to modify an int subclass
> instance in place? (That doesn't break math, preferably; I don't
> do arithmetic with these things but they are, after all, ints...)
>

Why is it an int subclass? Because there are places where you want to
use it as though it were an int? It might be easier to render those,
instead, eg by creating a __int__ method. (Or is it "an __int__
method"? Not sure.)

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


Re: any cherypy powred sites I can check out?

2013-05-18 Thread Chris Angelico
On Fri, May 17, 2013 at 10:09 AM, alex23  wrote:
> On May 17, 10:00 am, visphatesj...@gmail.com wrote:
>> is a cherrypy list accessible here on web thru google groups?
>
> Is an apology for your offensive response to Chris Angelico
> forthcoming?

In complete absence of all semblance of context, I do not see the
profane post as addressing me personally. But in lieu of an apology,
I'd settle for a little more content in the posts or some evidence
that he's read ESR Question. You know what, I'd settle for the latter
in lieu of pretty much anything.

I still think we should use that as a penance. Go and say three Our
Fathers, do a Stations of the Cross, and read esr's article on smart
questions. You are forgiven, my son.

ChrisA

(Caveat: I am not a Catholic, so I haven't much of a clue as to how
confession usually goes.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any cherypy powred sites I can check out?

2013-05-18 Thread Chris Angelico
On Sat, May 18, 2013 at 3:15 AM, Mark Lawrence  wrote:
> On 17/05/2013 01:00, visphatesj...@gmail.com wrote:
>>
>> fuck straight off
>>
>
> I assume you're the author of "How to win friends and influence people"?

Not quite. He's the author of the social networking version, "How to
win influence and friend people".

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


Re: How to write fast into a file in python?

2013-05-19 Thread Chris Angelico
On Sun, May 19, 2013 at 3:31 PM, Carlos Nepomuceno
 wrote:
> Thanks Dan! I've never used CPython or PyPy. Will try them later.

CPython is the "classic" interpreter, written in C. It's the one
you'll get from the obvious download links on python.org.

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


Re: Harmonic distortion of a input signal

2013-05-19 Thread Chris Angelico
On Sun, May 19, 2013 at 8:52 PM, Anti Log  wrote:
> total distortion of a harmonics

I selected this part of your post, right-clicked, and Chrome offered
to do a Google search for those words. And, surprise surprise, the
first hit is a page that appears to have the mathematics behind it.
Now, I don't know how much you trust Google and Wikipedia, but I'm
sure you can confirm the maths in some other way.

My guess is that there's no function in numpy to do what you're
asking... but it shouldn't be too hard to render the formula/e given
into Python code. Python's pretty expressive when it comes to algebra.
:)

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


Re: Please help with Threading

2013-05-19 Thread Chris Angelico
On Mon, May 20, 2013 at 7:46 AM, Dennis Lee Bieber
 wrote:
> On Sun, 19 May 2013 10:38:14 +1000, Chris Angelico 
> declaimed the following in gmane.comp.python.general:
>> With interpreted code eg in CPython, it's easy to implement preemption
>> in the interpreter. I don't know how it's actually done, but one easy
>> implementation would be "every N bytecode instructions, context
>> switch". It's still done at a lower level than user code (N bytecode
>
> Which IS how the common Python interpreter does it -- barring the
> thread making some system call that triggers a preemption ahead of time
> (even time.sleep(0.0) triggers scheduling). Forget if the default is 20
> or 100 byte-code instructions -- as I recall, it DID change a few
> versions back.

Incidentally, is the context-switch check the same as the check for
interrupt signal raising KeyboardInterrupt? ISTR that was another
"every N instructions" check.

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


Re: Question about ast.literal_eval

2013-05-20 Thread Chris Angelico
On Mon, May 20, 2013 at 5:05 PM, Frank Millman  wrote:
> Hi all
>
> I am trying to emulate a SQL check constraint in Python. Quoting from the
> PostgreSQL docs, "A check constraint is the most generic constraint type. It
> allows you to specify that the value in a certain column must satisfy a
> Boolean (truth-value) expression."
>
> The problem is that I want to store the constraint as a string, and I was
> hoping to use ast.literal_eval to evaluate it, but it does not work.
>
 x = 'abc'
 x in ('abc', xyz')
> True
 b = "x in ('abc', 'xyz')"
 eval(b)
> True
 from ast import literal_eval
 literal_eval(b)
> ValueError: malformed node or string: <_ast.Compare object at ...>
>
> Is there a safe way to do what I want? I am using python 3.3.

An SQL constraint has a whole lot that Python can't do conveniently,
and vice versa, so I think you do yourself a disservice by trying to
tie yourself to that.

The problem here is that 'in' is an operator, so this is not a
literal. One possible solution would be to separate out your operator
(and have just a handful permitted), and then use ast.literal_eval for
just the second operand - something like this:

import ast
import operator
ops = {
  'in':lambda x,y: x in y,  # operator.contains has the args backwards
  '==':operator.eq, # or use '=' for more SQL-like syntax
  '<':operator.lt,
  '>':operator.gt,
}

op, value = 'in', "('abc', 'xyz')"
x = 'abc'

if ops[op](x,ast.literal_eval(value)):
  print("Constraint passed")
else:
  print("Ignore this one")

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


Re: Question about ast.literal_eval

2013-05-20 Thread Chris Angelico
On Mon, May 20, 2013 at 5:50 PM, Frank Millman  wrote:
> On 20/05/2013 09:34, Carlos Nepomuceno wrote:
>> Why don't you use eval()?
>>
>
> Because users can create their own columns, with their own constraints.
> Therefore the string is user-modifiable, so it cannot be trusted.

Plenty of reason right there :)

Is it a requirement that they be able to key in a constraint as a
single string? We have a similar situation in one of the systems at
work, so we divided the input into three(ish) parts: pick a field,
pick an operator (legal operators vary according to field type -
integers can't be compared against regular expressions, timestamps can
use >= and < only), then enter the other operand. Sure, that cuts out
a few possibilities, but you get 99.9%+ of all usage and it's easy to
sanitize.

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


Re: Question about ast.literal_eval

2013-05-20 Thread Chris Angelico
On Mon, May 20, 2013 at 5:55 PM, Carlos Nepomuceno
 wrote:
> I understand your motivation but I don't know what protection 
> ast.literal_eval() is offering that eval() doesn't.

eval will *execute code*, while literal_eval will not. That's the
protection. With ast.literal_eval, all that can happen is that it
produces a single result value. In this case, unfortunately, that's
insufficient; a comparison needs to be done, ergo it's not an entire
literal. But something else in the ast module may be able to serve, or
maybe literal_eval can do the bulk of the work.

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


Re: Please help with Threading

2013-05-20 Thread Chris Angelico
On Mon, May 20, 2013 at 6:35 PM, Cameron Simpson  wrote:
>   _lock = Lock()
>
>   def lprint(*a, **kw):
> global _lock
> with _lock:
>   print(*a, **kw)
>
> and use lprint() everywhere?

Fun little hack:

def print(*args,print=print,lock=Lock(),**kwargs):
  with lock:
print(*args,**kwargs)

Question: Is this a cool use or a horrible abuse of the scoping rules?

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


Re: Please help with Threading

2013-05-20 Thread Chris Angelico
On Mon, May 20, 2013 at 7:54 PM, Cameron Simpson  wrote:
> On 20May2013 19:09, Chris Angelico  wrote:
> | On Mon, May 20, 2013 at 6:35 PM, Cameron Simpson  wrote:
> | >   _lock = Lock()
> | >
> | >   def lprint(*a, **kw):
> | > global _lock
> | > with _lock:
> | >   print(*a, **kw)
> | >
> | > and use lprint() everywhere?
> |
> | Fun little hack:
> |
> | def print(*args,print=print,lock=Lock(),**kwargs):
> |   with lock:
> | print(*args,**kwargs)
> |
> | Question: Is this a cool use or a horrible abuse of the scoping rules?
>
> I carefully avoided monkey patching print itself:-)
>
> That's... mad! I can see what the end result is meant to be, but
> it looks like a debugging nightmare. Certainly my scoping-fu is too
> weak to see at a glance how it works.

Hehe. Like I said, could easily be called abuse.

Referencing a function's own name in a default has to have one of
these interpretations:

1) It's a self-reference, which can be used to guarantee recursion
even if the name is rebound
2) It references whatever previously held that name before this def statement.

Either would be useful. Python happens to follow #2; though I can't
point to any piece of specification that mandates that, so all I can
really say is that CPython 3.3 appears to follow #2. But both
interpretations make sense, and both would be of use, and use of
either could be called abusive of the rules. Figure that out. :)

The second defaulted argument (lock=Lock()), of course, is a common
idiom. No abuse there, that's pretty Pythonic.

This same sort of code could be done as a decorator:

def serialize(fn):
lock=Lock()
def locked(*args,**kw):
with lock:
fn(*args,**kw)
return locked

print=serialize(print)

Spelled like this, it's obvious that the argument to serialize has to
be the previous 'print'. The other notation achieves the same thing,
just in a quirkier way :)

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


Re: Please help with Threading

2013-05-20 Thread Chris Angelico
=On Mon, May 20, 2013 at 8:46 PM, Ned Batchelder  wrote:
> On 5/20/2013 6:09 AM, Chris Angelico wrote:
>>
>> Referencing a function's own name in a default has to have one of
>> these interpretations:
>>
>> 1) It's a self-reference, which can be used to guarantee recursion
>> even if the name is rebound
>> 2) It references whatever previously held that name before this def
>> statement.
>
>
> The meaning must be #2.  A def statement is nothing more than a fancy
> assignment statement.

Sure, but the language could have been specced up somewhat
differently, with the same syntax. I was fairly confident that this
would be universally true (well, can't do it with 'print' per se in
older Pythons, but for others); my statement about CPython 3.3 was
just because I hadn't actually hunted down specification proof.

> So your "apparently recursive" print function is no more
> ambiguous "x = x + 1".  The x on the right hand side is the old value of x,
> the x on the left hand side will be the new value of x.
>
> # Each of these updates a name
> x = x + 1
>
> def print(*args,print=print,lock=Lock(),**kwargs):
>   with lock:
> print(*args,**kwargs)

Yeah. The decorator example makes that fairly clear.

> Of course, if you're going to use that code, a comment might be in order to
> help the next reader through the trickiness...

Absolutely!!

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


Re: Question about ast.literal_eval

2013-05-20 Thread Chris Angelico
On Mon, May 20, 2013 at 11:26 PM, Frank Millman  wrote:
> 0 - for the first entry in the list, the word 'check' (a placeholder - it is
> discarded at evaluation time), for any subsequent entries the word 'and' or
> 'or'.
>
> 1 - left bracket - either '(' or ''.
>
> 5 - right bracket - either ')' or ''.

I think what you have is safe, but extremely complicated to work with.
Six separate pieces, and things have to be in the right slots... I
think you've spent too many "complexity points" on the above three
components, and you're getting too little return for them. What
happens if the nesting is mucked up? Could get verrry messy to check.

Combining multiple conditions with a mixture of ands and ors is a
nightmare to try to explain (unless you just point to the Python docs,
which IMO costs you even more complexity points); the only safe option
is to parenthesize everything. The system I pushed for at work (which
was finally approved and implemented a few months ago) is more or less
this: conditions are grouped together into blocks; for each group, you
can choose whether it's "all" or "any" (aka and/or), and you choose
whether the overall result is all-groups or any-group. That still
costs a few complexity points (and, btw, our *actual* implementation
is a bit more complicated than that, but I think we could cut it down
to what I just described here without loss of functionality), but it
gives the bulk of what people will actually want without the
complexities of point-and-click code.

The downside of that sort of system is that it requires a two-level
tree. On the flip side, that's often how people will be thinking about
their conditions anyway (eg using a pair of conditions ">" and "<" to
implement a range check - conceptually it's a single check), so that
won't cost too much.

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


Re: Question about ast.literal_eval

2013-05-20 Thread Chris Angelico
On Tue, May 21, 2013 at 2:12 AM, Steven D'Aprano
 wrote:
> Personally, I would strongly suggest writing your own mini-
> evaluator that walks the list and evaluates it by hand. It isn't as
> convenient as just calling eval, but *definitely* safer.

Probably faster, too, for what it's worth - eval is pretty expensive.

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


Re: Please help with Threading

2013-05-20 Thread Chris Angelico
On Tue, May 21, 2013 at 11:44 AM, 8 Dihedral
 wrote:
> OK, if the python interpreter has a global hiden print out
> buffer of ,say, 2to 16 K bytes, and all  string print functions
> just construct the output string from the format to this string
> in an efficient low level way, then the next question
> would be that whether the uses can use functions in this
> low level buffer for other string formatting jobs.

You remind me of George.
http://www.chroniclesofgeorge.com/

Both make great reading when I'm at work and poking around with random
stuff in our .SQL file of carefully constructed mayhem.

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


Re: Question about ast.literal_eval

2013-05-21 Thread Chris Angelico
On Tue, May 21, 2013 at 4:46 PM, Frank Millman  wrote:
> You may be right, Chris, but I don't think my approach is all that bad.

Frankly, I'm not altogether convinced that our approach is right
either :) But like the Oracle in the Matrix, I'm not here to push you
to one decision or another so much as to just put the options in front
of you and let you make up your own  mind. Except in a
few cases where I'm really certain of my ground (like "don't put any
untrusted data through eval()"...).

> The vast majority of tests will be simple - either a single line, or two
> lines for a range check, with no brackets at all.
>
> If the requirement is more complicated than that, well, I don't think the
> complication can be avoided, and at least this approach gives full control.

Yeah, and this is where the issue of complexity points comes in.
You're spending a lot of them on functionality that most users won't
even use, and those who do will use only occasionally. You're forcing
them to match their brackets (not just have the same number of each
type, but also to get the nesting correct), and according to your
current spec, there can be no more than one open/close bracket at each
condition, so they'll have to arbitrarily add dummy conditions to make
certain forms of nesting work. You're exposing a lot of the underlying
interpreter, while forcing the user to dance wearing a body cast.
Sure, it can work, but it's unnecessarily hard.

> FWIW, I use the same approach to allow users to construct their own WHERE
> clauses in custom views. Again, the vast majority are simple, but there are
> times when it can get complicated.

Our alpha system is actually online, and we have exactly that system -
a query builder that renders down to a WHERE clause. If you're
curious, message me offline and I'll give you the URL.

> The proof of the pudding will be when I try to get ordinary users to get
> their own hands dirty - I am not there yet. If I ever get this released, the
> business model will be free software, but support will be charged for. So if
> a user gets out of his/her depth, there will be assistance available.
>
> Time will tell who is right ... ;-)

Who is right, and who is dead. Hey, are you aware that both Steven and
I come from Australia, and that we are used to having people not trust
us? Truly, you have a dizzying intellect!

ChrisA
... couldn't resist...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run a python script twice randomly in a day?

2013-05-21 Thread Chris Angelico
On Tue, May 21, 2013 at 11:12 AM, Cameron Simpson  wrote:
> Ok, good. Some minor remarks:
>
> Personally, I always use:
>
>   #!/bin/sh
>
> instead of requiring bash. All UNIX systems have sh, bash is only
> common. And even when present, it may not be in /bin. /bin/sh is
> always there, and unless you're doing something quite unusual, it
> works just fine.

Also, on many systems, /bin/sh is a much lighter interpreter than bash
(eg Debian uses dash). It's more efficient to use that when you can,
even if you use bash for your login shell.

> On 20May2013 15:05, Avnesh Shakya  wrote:
> | but when I m using like
> |
> | import random
> | a = random.randrange(0, 59)
> | */a * * * * bash /home/avin/cronJob/test.sh
> | then it's showing error becose of varable 'a', so now how can i take
> | variable?

You put that into your crontab? I do not think this means what you
think it means; cron does not execute arbitrary Python code.

> - randrange() is like other python ranges: it does not include the end value.
>   So your call picks a number from 0..58, not 0..59.
>   Say randrange(0,60). Think "start, length".

Nitpick: It's not start, length; it's start, stop-before. If the start
is 10 and the second argument is 20, you'll get numbers from 10 to 19.
But your conclusion is still accurate :)

ChrisA
(two Princess Bride references in as many threads, doing well!)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please help

2013-05-21 Thread Chris Angelico
On Tue, May 21, 2013 at 6:38 PM,   wrote:
> WAP in python to accept a list of words on STDIN and searches for a line 
> containing all five vowels(a,e,i,o,u)

Homework.

Have a shot at it yourself, post your code, show that you can put in
some effort. Otherwise we won't see much reason to put in effort for
you.

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


Re: sympy.nsimplify

2013-05-21 Thread Chris Angelico
On Tue, May 21, 2013 at 6:26 PM, Steven D'Aprano
 wrote:
> For maths nerds like me, this is too cool for words:
>
> http://www.johndcook.com/blog/2013/04/30/recognizing-numbers/

It is indeed, very cool. I think I need to conjure an excuse to use
this someplace.

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


  1   2   3   4   5   6   7   8   9   10   >