Re: Why did Quora choose Python for its development?

2011-05-23 Thread Stefan Behnel

Beliavsky, 20.05.2011 18:39:

I thought this essay on why one startup chose Python was interesting.


Since everyone seems to be hot flaming at their pet languages in this 
thread, let me quickly say this:


Thanks for sharing the link.

Stefan

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Octavian Rasnita

From: "Daniel Kluev" 

Moreover, you are comparing apples to oranges here, and then
complaining that apples somehow turned out to be not oranges.
If we take python way of defining dicts and check it in perl, we find
that it is not supported, so obviously perl is non-intuitive and does
not support clear and easy way of defining hashes from list of
key-value pairs:
@l = ([1, 2], [3, 4],);
%d = @l;
for $k ( keys %d ) { print "$k\n"; }

which outputs single ARRAY(0x804e158) instead of proper 1, 3, as it
does in python:


dict([[1,2], [3,4]]).keys()

[1, 3]

This is yet another example that you are just trolling here, making
silly and unbacked claims, and ignoring any valid arguments you
receive.



You are showing a code but tell another thing. If it would be as you said, I 
should have said that if in Perl a dictionary is made from a list using

%d = @l;

then in Python it should be
l = d

because it would be more nice. But I didn't say that. I said that it would 
be nice to be able to use something like

d = dict(l)

using the Python "dict" statement for creating dicts.

And OK, Python needs another pair of brackets for doing that and this is no 
problem, but the result is that the Python's syntax is not as shorter and 
nice as Perl's, for the same thing.

This is what that I said.

And you are telling that in Perl should be used an even more complicated and 
ugly syntax just for beeing the same as in Python just for showing that I am 
wrong, but I was comparing just the shortness and cleraness of the code.


So, again, in Perl is just:

%d = @l;

Please tell me if Python has a syntax which is more clear than this for 
doing this thing.

It doesn't matter if it is different or if it follows another syntax.

And again, I am not trolling anything. I am just defending a language which 
has a clearer syntax for doing some things, and a shorter code for other 
things, and which uses less braces and brackets than Python for other 
things, and which has a single-recommended way for doing some things, even 
though other list members were trolling about Perl, but nobody said 
something against.


Octavian

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Octavian Rasnita

From: "Daniel Kluev" 
On Mon, May 23, 2011 at 10:17 PM, Octavian Rasnita  
wrote:

From: "Daniel Kluev" 
Aha, so with other words that ORM doesn't have that feature.
DBIX::Class also use the DateTime module, but it can use it directly,
without needing to write more code for that, and it can also return
localized dates.


Once again. ORMs return _python builtin type_. Localization is not
their responsibility, and plugging it there is code bloat, rather than
feature. Sure you may ask ORM to handle JSONRPC requests on its own,
but ORM responsibility is to map RDBMS features to language objects.


Who said that? The ORM responsability is to map RDBMS to the objects you 
need, not to the language objects.
If the ORM can do that directly by just adding a configuration instead of 
needing to manually use of other modules, why is this bloat? You add that 
configuration only if you need it, not always, and it is much more simple.



All good python packages limit their functionality to specific field,
so you could choose one you prefer for each different task
independently.



All the Perl modules do the same, but some of the Perl modules accept 
plugins that make easier the collaboration of different modules which are 
needed often, and the need of localizing the date is a feature used often.


without needing to load the DateTime module manually and to initialize 
the DateTime object manually...


This is basically stating that you didn't read the code I posted.
Where did you ever find "initialize the DateTime object manually"?
Sorry, but its pointless to discuss anything if you don't want to even
read properly examples you receive.



You told that you need to use another module for localizing the date because 
the ORM returns just a language date object that doesn't do that.



Octavian

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Octavian Rasnita

From: "Ulrich Eckhardt" 
Ahem, is this Java the language that a certain, well-known service 
provider

is getting screwed over hard currently, because they forgot to read the
fineprint in the declaration of freedom? And this Objective C, isn't this
the language that GCC had support for since before it properly supported
C++, and that on a multitude of targets?



Someone also said that C# can be used under Mono and even though this is 
true, C# still remains a proprietary language that can be totally changed if 
MS wants that, as well as Objective C can be changed if Apple wants that.
So what matters is if the most important developers for a specific 
language/platform are releasing the code as open source or they keep it 
proprietary and I don't see a big number of programmers developing code in 
C# and Objective C.


About Java... you may be right. :-)

Octavian




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


Re: Make Python "portable" by default! (Re: Python IDE/text-editor)

2011-05-23 Thread JussiJ
On Apr 17, 7:13 pm, Wolfgang Keller  wrote:

> > You can't run Python programs without a Python interpreter installed.
>
> Wrong.
>
> See e.g.http://www.portablepython.com/

In this case Python is still installed on the machine.

It may not be installled on the PC's hard disk but it is certainly
is installed on the USB stick.

In other words the act of inserting the USB actually results in
the software being 'Installed' (i.e. being made available) on
the PC.

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread John Bokma
"Octavian Rasnita"  writes:

> From: "Daniel Kluev" 
> a = [1,2]
> dict([a])
>
> Yes, but
>
> d = dict([a])
>
> is not so nice as
>
> $d = @a;

That will give you the number of elements in @a. What you (probably)
mean is %hash = @array;

-- 
John Bokma   j3b

Blog: http://johnbokma.com/Perl Consultancy: http://castleamber.com/
Perl for books:http://johnbokma.com/perl/help-in-exchange-for-books.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English Idiom in Unix: Directory Recursively

2011-05-23 Thread Chris Angelico
On Tue, May 24, 2011 at 2:20 PM, Xah Lee  wrote:
> why don't you file a bug report? In GNU Emacs 23.2, it's under the
> Help menu. I suppose it's the same in other emacs distro.
>

Because I do not consider its behaviour to be errant. And I suspect
its main developers won't either. That's why I suggested you grab the
sources and make The Perfect Emacs.

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


Re: English Idiom in Unix: Directory Recursively

2011-05-23 Thread Xah Lee
On May 22, 4:32 pm, Chris Angelico  wrote:
> On Mon, May 23, 2011 at 9:17 AM, Xah Lee  wrote:
> > the context is this: In emacs directory manager (aka dired), when you
> > call dired-do-delete on a directory, emacs prompts, this way:
> > “Recursive delete of xx? (y or n)”
>
> But in order to make your point (such as it is), you are ignoring the
> fact that there are other uses of the term 'recurse' or 'recursive',
> and consistency and clarity are important. I don't see emacs offering
> me a chance to do a non-recursive delete; the only issue here seems to
> be that it's explicit that it is going to destroy an entire branch of
> the directory tree. If this is such a problem, grab the emacs sources
> and change that string - it probably occurs in exactly one place in
> the code. Voila! You now have The One True Perfect Emacs, the ultimate
> text editor, because it no longer tells you that it's working
> recursively.
>
> *removes tongue from cheek after saying that last sentence*
>
> Chris Angelico

why don't you file a bug report? In GNU Emacs 23.2, it's under the
Help menu. I suppose it's the same in other emacs distro.

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 10:10 PM, Octavian Rasnita  wrote:
> is not so nice as
>
> $d = @a;

It is 'not so nice' only in your perception. Python clearly defines
dict as container of (key, value) pairs, and therefore its constructor
expects such pairs. Adding unjustified arbitrary ways to guess such
pairs out of linear list is exactly what is being bashed here. Is is
considered to be wrong and bad.

Moreover, you are comparing apples to oranges here, and then
complaining that apples somehow turned out to be not oranges.
If we take python way of defining dicts and check it in perl, we find
that it is not supported, so obviously perl is non-intuitive and does
not support clear and easy way of defining hashes from list of
key-value pairs:

@l = ([1, 2], [3, 4],);
%d = @l;
for $k ( keys %d ) { print "$k\n"; }

which outputs single ARRAY(0x804e158) instead of proper 1, 3, as it
does in python:

>>> dict([[1,2], [3,4]]).keys()
[1, 3]

This is yet another example that you are just trolling here, making
silly and unbacked claims, and ignoring any valid arguments you
receive.

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Octavian Rasnita

From: "Daniel Kluev" 
a = [1,2]
dict([a])

Yes, but

d = dict([a])

is not so nice as

$d = @a;

because it has exactly those numerous number of params and brackets which is 
used as a reason for bashing Perl and an aditional "dict" word.


Octavian

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


Re: Multiple file select with tkFileDialog passes back 'decorated' strings (sometimes)

2011-05-23 Thread Gabriel Genellina

En Mon, 23 May 2011 10:00:53 -0300, Alex van der Spek 
escribió:

I switched from Mark Hammonds pywin32 extensions for file choosers as  
the multiselect there seems to crash on me when selecting more than a  
few dozen. Using Tk now. Works well but the resulting string passed back  
seems to 'decorated' when the files are on local disk and not decorated  
when retrieved over a USB interface from an external disk?


I do this:


From local disk I get back:


'{file1.bin} {file2.bin}'


From external disk I get back:


'file1.bin file2.bin'

I can handle/parse both, not an issue but it raises the question: Are  
these the only two possibilities? Is it the same across platforms (I use  
Python 2.7 on Win Vista)?


An old bug. See http://bugs.python.org/issue5712 for a workaround.

--
Gabriel Genellina

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


Re: Abandoning Python

2011-05-23 Thread rantingrick
On May 23, 7:04 pm, Gregory Ewing  wrote:
> Falcon seems to collect programming paradigms the way Perl
> collects language features, i.e. by just munging them all
> together and bending parts until they fit.

Not that i am picking on anyone here...

but...

Why is okay to rip apart Perl with jagged metal teeth (and not that i
am complaining mind you) however if anyone even hints about Ruby being
somewhat ...oh let's say "asinine" or how about "redundant"...  all
the Ruby trolls crawl out the woodwork and start bashing you in the
head with a recursive iterator? Do they not understand that Ruby is
nothing more than Perl's "mini-me" bent on displacing the glory of
Python with Perl style obfuscation, squiggly variable decorators, and
redundant syntaxes so horrific that even Tim Toady would blush in
embarrassment?

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


Re: Unit testing beginner question

2011-05-23 Thread Roy Smith
In article ,
 Ian Kelly  wrote:

> This would work:
> 
> self.assertRaises(TypeError, lambda: self.testListNone[:1])

If you're using the version of unittest from python 2.7, there's an even 
nicer way to write this:

with self.assertRaises(TypeError):
self.testListNone[:1]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English Idiom in Unix: Directory Recursively

2011-05-23 Thread Steven D'Aprano
On Mon, 23 May 2011 20:56:03 +0200, Rikishi42 wrote:

> On 2011-05-20, Steven D'Aprano 
> wrote:
>> On Thu, 19 May 2011 22:13:14 -0700, rusi wrote:
>>
>>> [I agree with you Xah that recursion is a technical word that should
>>> not be foisted onto lay users.]
>>
>> I think that is a patronizing remark that under-estimates the
>> intelligence of lay people and over-estimates the difficulty of
>> understanding recursion.
> 
> Why would you presume this to be related to intelligence? The point was
> not about being *able* to understand, but about *needing* to understand
> in order to use.


Maybe they don't "need" to understand recursion. So what?

Recursion is a perfectly good English word, no more technical than 
"accelerate" or "incinerate" or "dissolve" or "combustion". Do people 
need to know the word "combustion" when they could say "burn" instead? Do 
they need to know the words "microwave oven" when they could be saying 
"invisible rays cooking thing"?

I wonder whether physicists insist that cars should have a "go faster 
pedal" because ordinary people don't need to understand Newton's Laws of 
Motion in order to drive cars?

Who are you to say that people shouldn't be exposed to words you deem 
that they don't need to know?



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


Re: Abandoning Python

2011-05-23 Thread Gregory Ewing

Steven D'Aprano wrote:

On Mon, 23 May 2011 13:11:40 +1200, Gregory Ewing wrote:


...until you want to read someone *else's* code, that is.


The same might be said about Python, which supports procedural, OO and 
functional styles out of the box.


But it only uses *one* syntax and core set of concepts to
cover all of those. Unlike, apparently, Falcon... take a
look at this page concerning how Falcon approaches functional
programming (but don't look for too long or your eyes may
begin to bleed...)

http://falconpl.org/index.ftd?page_id=sitewiki&prj_id=_falcon_site&sid=wiki&pwid=Survival%20Guide&wid=Survival%3AFunctional+programming

Falcon seems to collect programming paradigms the way Perl
collects language features, i.e. by just munging them all
together and bending parts until they fit.

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


Re: Is there a better way to solve this?

2011-05-23 Thread Steven D'Aprano
On Mon, 23 May 2011 11:55:08 -0700, kracekumar ramaraju wrote:

> You can use sizeof function,

Who are you talking to, and what question did they ask?

Please always quote enough of the post that you are replying to to 
establish context.


 a=12234
 b=23456.8
 a.__sizeof__()
> 12
 b.__sizeof__()
> 16
> So sizeof int is 12 bytes and float is 16 bytes

You shouldn't be calling special methods directly (except under unusual 
circumstances). That's like calling s.__len__() instead of len(s).

The public function for getting the size of an object is in the sys 
module:

sys.getsizeof(a)



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


Re: Unit testing beginner question

2011-05-23 Thread Ian Kelly
On Mon, May 23, 2011 at 4:30 PM, Andrius  wrote:
> and I am expecting test to pass, but I am getting exception:
> Traceback (most recent call last):
>    self.assertRaises(TypeError, self.testListNone[:1])
> TypeError: 'NoneType' object is unsubscriptable
>
> I thought that assertRaises will pass since TypeError exception will
> be raised?

The second argument to assertRaises must be a function that
assertRaises will call.  assertRaises can't catch the error above
because it is raised when the argument is evaluated, before
assertRaises has even been called.

This would work:

self.assertRaises(TypeError, lambda: self.testListNone[:1])

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


Re: Unit testing beginner question

2011-05-23 Thread Andrius A
That was quick! Thanks Ian


On 23 May 2011 23:46, Ian Kelly  wrote:

> On Mon, May 23, 2011 at 4:30 PM, Andrius  wrote:
> > and I am expecting test to pass, but I am getting exception:
> > Traceback (most recent call last):
> >self.assertRaises(TypeError, self.testListNone[:1])
> > TypeError: 'NoneType' object is unsubscriptable
> >
> > I thought that assertRaises will pass since TypeError exception will
> > be raised?
>
> The second argument to assertRaises must be a function that
> assertRaises will call.  assertRaises can't catch the error above
> because it is raised when the argument is evaluated, before
> assertRaises has even been called.
>
> This would work:
>
> self.assertRaises(TypeError, lambda: self.testListNone[:1])
>
> Cheers,
> Ian
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange behaviour of input() function (Python 3.2)

2011-05-23 Thread Chris Angelico
On Tue, May 24, 2011 at 1:44 AM, Aleksander Pietkiewicz
 wrote:
> Hello,
> I have googled your email address, I hope it is not a problem.
> Thank you for your help!

I figured you would get it from my post, but either way works! My
email address is fairly well known. Sorry for the delay in response;
you caught me while I was asleep. :) I'm now responding on-list so
that other people can help.

> I agree that can be very specific bug, I suspect it is matter of coding. I'm
> emailing you a *.py file as you asked and screenshot showing script being
> run.

Unfortunately my Windows install doesn't have internationalization
support, which may be an issue here. I ran your 'couting.py' and got
errors back:
Traceback (most recent call last):
  File "foo.py", line 11, in 
n=input("Naci\u015bnij Enter aby zako\u0144czy\u0107...")
  File "C:\python32\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character '\u015b' in position
4: character maps to 

So I'm guessing that codepage 437 is just plain wrong. But that
shouldn't affect your system.

> As you can see this problem occurs only with 3rd party software (like Komodo
> Edit).
> In, addition when I'm using Komodo or Notepad++ and input() function, Python
> miscount bytes. See attached.
> Once again thank you for your help!
> Kind regards,
> Aleksander Pietkiewicz

My suspicion here is that your editor is saving using one encoding,
and Python is expecting another. I recommend you put an encoding
marker at the top of your source file:

# coding=utf-8

See http://www.python.org/dev/peps/pep-0263/ for details. With this in
place, you should be able to guarantee that the bytestream is parsed
the same way by editor and interpreter.

Unfortunately that's all I could offer; I was unable to duplicate the
exact problem you were seeing. The contents of 'couting.py' are simple
enough, so I'll paste here in case anyone can spot a problem:


s = (input('Enter something : '))
z = input('Enter something : ')

print('Length of the string s is', len(s))
print('Length of the string z is', len(z))

print(s)
print(z)


Point to note: On my Windows XP, the string lengths are one higher
than expected, and they include a \r at the end. Is there any way that
this could trigger a Unicode parse failure??

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


Unit testing beginner question

2011-05-23 Thread Andrius
Hello,

would be gratefull for the explonation.

I did a simple test case:

def setUp(self):
  self.testListNone = None

def testListSlicing(self):
  self.assertRaises(TypeError, self.testListNone[:1])

and I am expecting test to pass, but I am getting exception:
Traceback (most recent call last):
self.assertRaises(TypeError, self.testListNone[:1])
TypeError: 'NoneType' object is unsubscriptable

I thought that assertRaises will pass since TypeError exception will
be raised?

Ta,
Andrius



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


Re: Functional Programing: stop using recursion, cons. Use map & vectors

2011-05-23 Thread Deeyana
On Mon, 23 May 2011 00:52:07 -0700, asandroq wrote:

> On May 23, 4:29 am, Deeyana  wrote:
>>
>> You might be interested in Clojure, then. Lists are more abstracted,
>> like in Scheme, and vectors and also dictionaries/maps and sets are
>> first class citizens along side lists. And unlike Scheme, Clojure has
>> good library/host interop support. You can write real-world
>> applications in it without spontaneously combusting.
> 
>  Nonsense.

Classic unsubstantiated and erroneous claim. Nothing that I write is ever 
"nonsense".

> Several Scheme systems have excellent FFIs with more than "good library/
> host interop support".

Classic unsubstantiated and erroneous claim. Scheme does not come OOTB 
with any suitable libraries for host interop and though it can make calls 
to C libraries, doing so is awkward and involves difficulties with the 
impedance mismatch between Scheme's data structures and C's char *, void 
*, int, double, array, etc. types. To top it off, C lacks automatic 
memory management, which means you'll have to concern yourself with 
manually disposing of allocated data structures used in interop. (Or, 
worse, things will get garbage collected by the Scheme runtime that the 
Scheme code no longer references, but the C library is still using, and 
bam! SIGSEGV.)

And then you gain what, the diverse mix of platform-specific, unportable, 
sometimes-wonky C libraries?

Versus Clojure immediately granting simple, easy to use access to a large 
standard Java library that works more or less the same across a broad 
range of host platforms, as well as the rest of the JVM library 
ecosystem, which mostly has the same qualities. Clojure being designed 
for the JVM, there's much less of an impedance mismatch with Java's 
types, and the interop call syntax is easy to master and won't set your 
hair on fire.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way to solve this?

2011-05-23 Thread Terry Reedy

On 5/23/2011 2:55 PM, kracekumar ramaraju wrote:

You can use sizeof function,


Appears not to be in manuals, that I could find. As a special method, it 
is intended to be called through sys.getsizeof.



a=12234
b=23456.8
a.__sizeof__()

12

b.__sizeof__()

16
So sizeof int is 12 bytes and float is 16 bytes


Depends on system. On my winxp machine, ints are 14 bytes.

>>> import sys
>>> size = sys.getsizeof
>>> size(1)
14
>>> size(1.0)
16
>>> size([])
36
>>> size([1,2,3])
48

--
Terry Jan Reedy

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


Re: Condition.wait(timeout) oddities

2011-05-23 Thread Floris Bruynooghe
On Monday, 23 May 2011 17:32:19 UTC, Chris Torek  wrote:
> In article
> <94d1d127-b423-4bd4...@glegroupsg2000goo.googlegroups.com>
> Floris Bruynooghe   wrote:
> >I'm a little confused about the corner cases of Condition.wait() with a
> >timeout parameter in the threading module.
> >
> >When looking at the code the first thing that I don't quite get is that
> >the timeout should never work as far as I understand it.  .wait() always
> >needs to return while holding the lock, therefore it does an .acquire()
> >on the lock in a finally clause.  Thus pretty much ignoring the timeout
> >value.
> 
> It does not do a straight acquire, it uses self._acquire_restore(),
> which for a condition variable, does instead:
> 
> self.__block.acquire()
> self.__count = count
> self.__owner = owner
> 
> (assuming that you did not override the lock argument or passed
> in a threading.RLock() object as the lock), due to this bit of
> code in _Condition.__init__():
> 
> # If the lock defines _release_save() and/or _acquire_restore(),
> # these override the default implementations (which just call
> # release() and acquire() on the lock).  Ditto for _is_owned().
> [snippage]
> try:
> self._acquire_restore = lock._acquire_restore
> except AttributeError:
> pass

Ah, I missed this bit in the __init__() and the fact that RLock provides the 
_acquire_restore() and _release_save().  I was wondering why they jumped around 
via self._acquire_restore() and self._release_save(), it seemed rather a lot of 
undocumented effort for custom locks.


> That is, lock it holds is the one on the "blocking lock" (the
> __block of the underlying RLock), which is the same one you had
> to hold in the first place to call the .wait() function.
> 
> To put it another way, the lock that .wait() waits for is
> a new lock allocated for the duration of the .wait() operation:

That makes more sense now.  I knew that really, just never quite realised until 
you wrote this here so clearly.  Thanks.

So essentially the condition's lock is only meant to lock the internal state of 
the condition and not meant to be acquired for long times outside that as 
.wait() calls will not be able to return.  My confusion started from looking at 
queue.Queue which replaces the lock with a regular lock and uses it to lock the 
Queue's resource.  I guess the Queue's mutex satisfies the requirement of never 
being held for long times.


> >The second issue is that while looking around for this I found two bug
> >reports: http://bugs.python.org/issue1175933 and
> >http://bugs.python.org/issue10218.  Both are proposing to add a return
> >value indicating whether the .wait() timed out or not similar to the
> >other .wait() methods in threading.  However the first was rejected
> >after some (seemingly inconclusive) discussion.
> 
> Tim Peters' reply seemed pretty conclusive to me. :-)

Which is why I'm surprised that it now does.


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


Re: Multiprocessing: don't push the pedal to the metal?

2011-05-23 Thread Adam Tauno Williams
On Mon, 2011-05-23 at 12:51 -0700, John Ladasky wrote:
> On May 23, 2:50 am, Adam Tauno Williams 
> wrote:
> > I develop an app that uses multiprocessing heavily.  Remember that all
> > these processes are processes - so you can use all the OS facilities
> > regarding processes on them.  This includes setting nice values,
> > schedular options, CPU pinning, etc...
> That's interesting.  Does code exist in the Python library which
> allows the adjustment of CPU pinning and nice levels?  I just had
> another look at the multiprocessing docs, and also at os.subprocess.
> I didn't see anything that pertains to these issues.

"in the Python library" - no.  All these types of behaviors are platform
specific.

For example you can set the "nice" (priority) of a UNIX/LINUX process
using the nice method from the os module.  Our workflow engine does this
on all worker processes it starts - it sends the workers to the lowest
priority.


from osimport nice as os_priority
...
try:
os_priority(20)
except Exception, e:
...

I'm not aware of a tidy way to call sched_setaffinity from Python; but
my own testing indicates that the LINUX kernel is very good at figuring
this out on its own so long as it isn't swamped.  Queuing, rather than
starting, additional workflows if load average exceeds X.Y and setting
the process priority of workers to very-low seems to work very well.

There is  for setting affinity,
but I haven't used it.

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


Re: Is there a better way to solve this?

2011-05-23 Thread David Robinow
On Mon, May 23, 2011 at 2:55 PM, kracekumar ramaraju
 wrote:
> You can use sizeof function,
 a=12234
 b=23456.8
 a.__sizeof__()
> 12
 b.__sizeof__()
> 16
> So sizeof int is 12 bytes and float is 16 bytes

I'm not sure what you're trying to show here, but try the following in
Python 3.2

>>> a = 
>>> for i in range(5):
...  a*= 10
...  a.__sizeof__()
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Odp: Re: Re: Strange behaviour of input() function (Python 3.2)

2011-05-23 Thread sunrrrise
Hello,
I have checked another computer (WinXP, 32b) with Komodo Edit 6.1 and 
ActiveState Python 3.2 - problem still occurs.

Have you received my email?

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


Re: Multiprocessing: don't push the pedal to the metal?

2011-05-23 Thread John Ladasky
On May 23, 2:50 am, Adam Tauno Williams 
wrote:

> I develop an app that uses multiprocessing heavily.  Remember that all
> these processes are processes - so you can use all the OS facilities
> regarding processes on them.  This includes setting nice values,
> schedular options, CPU pinning, etc...

That's interesting.  Does code exist in the Python library which
allows the adjustment of CPU pinning and nice levels?  I just had
another look at the multiprocessing docs, and also at os.subprocess.
I didn't see anything that pertains to these issues.

> > Each CPU (or core) has its own execution cache. If you can keep one
> > thread running on the same core all the time, it will benefit more
> > from that cache than if it has to keep flitting from one to another.
>
> +1


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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Octavian Rasnita
From: "Terry Reedy" 
> On 5/23/2011 4:49 AM, Octavian Rasnita wrote:
> 
>> But let's remember from what this discussion started. This is not a
>> Python critique, because each language has its own ways.
>> I just wanted to show that the fact that "there is more than one way to
>> do it" in Perl and that "there is a single way" in Python are just
>> buzzwords,
> 
> Agreed. The latter is simply incorrect for Python and I don't know why 
> people say that. The statement from the Zen of Python is as follows:
> "There should be one-- and preferably only one --obvious way to do it."
> where 'it' is some reasonable common operation. This is a statement of 
> *intent* that is opposed to "All possible ways of doing things should be 
> included". The key word that people too often omit is *obvious* (once 
> one learns Python). There are usually, of necessity, multiple ways to do 
> something, but for common operations, there should be one way that is 
> obvious to the experienced Python programmer.

Yes you are right. And it is exactly the same in case of experienced Perl 
programmers.

There is even a Perl book regarding the best practices, with many 
recommendations for the obvious way to do various things, and there is the 
module Perl::Critic with its command line percritic that follows those best 
practices very closely, so it is also just a buzzword that "there is more than 
one way to do it" for experienced Perl programmers.


> > because this was an example where in Python there are many
>> ways to do it while in Perl there is a single way used usually, which is
>> also more simple.
> 
> Here I disagree. As I replied before, you are either ignoring the 
> obvious Python way or talking about a rare need.


I was talking about the method of creating a dictionary from an array which is 
much shorter and clear in Perl than in Python, and if you are using this very 
rarely, others might need to use it often.

Octavian



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


Re: English Idiom in Unix: Directory Recursively

2011-05-23 Thread Rikishi42
On 2011-05-20, Steven D'Aprano  wrote:
> On Thu, 19 May 2011 22:13:14 -0700, rusi wrote:
>
>> [I agree with you Xah that recursion is a technical word that should not
>> be foisted onto lay users.]
>
> I think that is a patronizing remark that under-estimates the 
> intelligence of lay people and over-estimates the difficulty of 
> understanding recursion.

Why would you presume this to be related to intelligence?
The point was not about being *able* to understand, but about *needing* to
understand in order to use. 



-- 
When in doubt, use brute force.
-- Ken Thompson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English Idiom in Unix: Directory Recursively

2011-05-23 Thread Rikishi42
On 2011-05-20, Hans Georg Schaathun  wrote:

>:  It starts with the misconception (or should I say confusion?) between
>:  performing a recursive job and using a recursive tool to do it. And then it
>:  blazes off in these huge discusions about semantics to define a definition
>:  of an abstraction of a alleady theoretical problem.
>
> And explaining the source of the misconception and the varying use
> would be irrelevant?

It usually is, yes. And boring.



-- 
When in doubt, use brute force.
-- Ken Thompson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way to solve this?

2011-05-23 Thread kracekumar ramaraju
You can use sizeof function,
>>> a=12234
>>> b=23456.8
>>> a.__sizeof__()
12
>>> b.__sizeof__()
16
So sizeof int is 12 bytes and float is 16 bytes
-- 
http://mail.python.org/mailman/listinfo/python-list


I installed Python 3 on Fedora 14 By Downloading python3.2 bziped source tarball and install it according to the README, Now How shall I uninstalled python 3.2?

2011-05-23 Thread Varuna Seneviratna
I installed Python 3 By Downloading python3.2 bziped source tarball
and install it according to the README, Now How shall I uninstalled
python 3.2?

The README instructions are as below
  Build Instructions
--

On Unix, Linux, BSD, OSX, and Cygwin:

./configure
make
make test
sudo make install
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Condition.wait(timeout) oddities

2011-05-23 Thread Chris Torek
In article
<94d1d127-b423-4bd4-853c-d92da9ac7...@glegroupsg2000goo.googlegroups.com>
Floris Bruynooghe   wrote:
>I'm a little confused about the corner cases of Condition.wait() with a
>timeout parameter in the threading module.
>
>When looking at the code the first thing that I don't quite get is that
>the timeout should never work as far as I understand it.  .wait() always
>needs to return while holding the lock, therefore it does an .acquire()
>on the lock in a finally clause.  Thus pretty much ignoring the timeout
>value.

It does not do a straight acquire, it uses self._acquire_restore(),
which for a condition variable, does instead:

self.__block.acquire()
self.__count = count
self.__owner = owner

(assuming that you did not override the lock argument or passed
in a threading.RLock() object as the lock), due to this bit of
code in _Condition.__init__():

# If the lock defines _release_save() and/or _acquire_restore(),
# these override the default implementations (which just call
# release() and acquire() on the lock).  Ditto for _is_owned().
[snippage]
try:
self._acquire_restore = lock._acquire_restore
except AttributeError:
pass

That is, lock it holds is the one on the "blocking lock" (the
__block of the underlying RLock), which is the same one you had
to hold in the first place to call the .wait() function.

To put it another way, the lock that .wait() waits for is
a new lock allocated for the duration of the .wait() operation:

waiter = _allocate_lock()
waiter.acquire()
self.__waiters.append(waiter)
saved_state = self._release_save()

self._acquire_restore(saved_state)
# the last stmt is the "finally" clause, I've just un-indented it

which is entirely different from the lock that .wait() re-acquires
(and which you held when you called .wait() initially) before it
returns.

>The second issue is that while looking around for this I found two bug
>reports: http://bugs.python.org/issue1175933 and
>http://bugs.python.org/issue10218.  Both are proposing to add a return
>value indicating whether the .wait() timed out or not similar to the
>other .wait() methods in threading.  However the first was rejected
>after some (seemingly inconclusive) discussion.

Tim Peters' reply seemed pretty conclusive to me. :-)

>While the latter had
>minimal discussion and and was accepted without reference to the earlier
>attempt.  Not sure if this was a process oversight or what, but it does
>leave the situation confusing.

>But regardless I don't understand how the return value can be used
>currently: yes you did time out but you're still promised to hold the
>lock thanks to the .acquire() call on the lock in the finally block.

The return value is not generally useful for the reasons Tim Peters
noted originally.  Those are all still true even in the second
discussion.

>In my small brain I just can't figure out how Condition.wait() can both
>respect a timeout parameter and the promise to hold the lock on return. 

Remember, "two different locks". :-)  There is a lock on the state
of the condition variable itself, and then there is a lock on which
one actually waits.  On both entry to and return from .wait(), you
(the caller) hold the lock on the state of the condition variable,
so you may inspect it and proceed based on the result.  In between,
you give up that lock, so that other threads may obtain it and
change the state of the condition variable.

>It seems to me that the only way to handle the timeout is to raise an
>exception rather then return a value because when you get an exception
>you can break the promise of holding the lock.

That *would* be a valid way to implement a timeout -- to return with
the condition variable lock itself no longer held -- but that would
require changing lots of other code structure.
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing multiple files with with-context

2011-05-23 Thread Ian Kelly
On Sun, May 22, 2011 at 8:48 PM, Shunichi Wakabayashi
 wrote:
> One idea is using contextlib.nested(),
>
> from contextlib import nested
>
> with nested(*[open('list_%d.txt' % i, 'w') for i in range(LIST_LEN)]) as 
> fobjlist:
>  for i in range(1000):
>    fobjlist[random.randrange(LIST_LEN)].write(str(i)+"\n")
>
> with nested(*[open('dict_%s.txt' % k, 'w') for k in DICT_KEYS]) as fobjlist:
>  fobjdict = dict(zip(DICT_KEYS, fobjlist)) #convert list to dict
>  for i in range(1000):
>    fobjdict[random.choice(DICT_KEYS)].write(str(i)+"\n")
>
> On Python2.x, this is OK. but 3.x warns that nested() is deprecated.

Not merely deprecated.  It has already been removed in 3.2.

> Another idea is to make container classes having __exit__() myself.
>
> class MyList(list):
>  def __enter__(self):
>    return [ v.__enter__() for v in self ]
>  def __exit__(self, exc_type, exc_value, traceback):
>    ret = False
>    for v in self:
>      if v.__exit__(exc_type, exc_value, traceback):
>        ret = True
>        exc_type = exc_value = traceback = None
>    return ret

This has a number of subtle bugs in it:

1) Each context manager's __exit__ method is not loaded before the
corresponding __enter__ method is invoked.
2) If the second context manager's __enter__ method raises an
exception, the first context manager's __exit__ method is never
called, breaking the with statement guarantee.
3) The __exit__ methods are called in the same order that the
__enter__ methods were called.  Since they form a stack, they should
be called in the reverse order.

These highlight the complexity of handling context managers correctly,
which I think suggests that a custom implementation is probably a bad
idea.

> So, do you have another, more smart and pythonic way?

Copy the implementation of contextlib.nested to your own custom module
and use that.  The last revision prior to its removal is here:

http://hg.python.org/cpython/file/45506be44514/Lib/contextlib.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Terry Reedy

On 5/23/2011 4:49 AM, Octavian Rasnita wrote:


But let's remember from what this discussion started. This is not a
Python critique, because each language has its own ways.
I just wanted to show that the fact that "there is more than one way to
do it" in Perl and that "there is a single way" in Python are just
buzzwords,


Agreed. The latter is simply incorrect for Python and I don't know why 
people say that. The statement from the Zen of Python is as follows:

"There should be one-- and preferably only one --obvious way to do it."
where 'it' is some reasonable common operation. This is a statement of 
*intent* that is opposed to "All possible ways of doing things should be 
included". The key word that people too often omit is *obvious* (once 
one learns Python). There are usually, of necessity, multiple ways to do 
something, but for common operations, there should be one way that is 
obvious to the experienced Python programmer.


For instance, if you want to process the items of a collections, you can 
use normal recursion, tail recursion, while iteration, or for iteration. 
For the first three, you can use explicit or implicit conditions for 
flow control. (Implicit conditions are by try-except.) One can use 
various access methods to get the items. However, the one obvious, 
compact, and efficient way is 'for item in collection:'. This works with 
*any* collection with a proper __iter__ method.\


People accustomed to using tail recursion for this in other languages 
sometimes request that tail-call space optimization be added to make 
tail recursion a second 'obvious' way. Guido has refused because 1) 
there are real problems with the idea and 2) one obvious way is enough.


Similarly, the obvious way to define a function is a def statement. One 
alternative, which Guido allowed to be added for the specific purpose of 
passing simple functions as arguments in function calls, is a lambda 
expression. Guido has rejected requests to expand lambda expressions to 
general function definitions. Again, there are real problems and one 
obvious way is enough.


> because this was an example where in Python there are many

ways to do it while in Perl there is a single way used usually, which is
also more simple.


Here I disagree. As I replied before, you are either ignoring the 
obvious Python way or talking about a rare need.


--
Terry Jan Reedy

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


Re: Tkinter bug?

2011-05-23 Thread Ned Deily
In article 
<5790ee23-37d1-4cdd-b88b-a63c2b627...@k15g2000pri.googlegroups.com>,
 rusi  wrote:
> If I start turtle from idle,  and issue commands from there, there are
> all kinds of strange behaviors.

Have you tried starting IDLE with the "-n" switch?

http://docs.python.org/library/turtle.html

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

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


Re: Functional Programing: stop using recursion, cons. Use map & vectors

2011-05-23 Thread Antti J Ylikoski

On 23.5.2011 16:39, Pascal J. Bourguignon wrote:

torb...@diku.dk (Torben Ægidius Mogensen) writes:


Xah Lee  writes:



Functional Programing: stop using recursion, cons. Use map&  vectors.

〈Guy Steele on Parallel Programing〉
http://xahlee.org/comp/Guy_Steele_parallel_computing.html


This is more or less what Backus said in his Turing Award lecture about
FP.


Stop inflating his ego!  Next he'll quote Nobel prize winners...



Well said That inspired me to note:

LISP without recursion would be like a jet airplane without wings 
Recursion is an important part of the functional programming paradigm

(yes, I do know that LISP is not a purely functional language...)

LISP denotes, List Processing.  List Processing without cons ?  Ugh.

regards, andy

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


Tkinter bug?

2011-05-23 Thread rusi
If I start turtle from idle,  and issue commands from there, there are
all kinds of strange behaviors.
I cant pin down any properly but they all look like IO issues.

-- If the turtle window is hidden by the tkinter interpreter window,
none of what is drawn appears
-- If the turtle window is killed I get a
this window is not responding box
-- The window always shows as 'Non responding'

I therefore guess that the emacs-related behavior I asked about
earlier has little to do with emacs and more to do with tkinter on
windows.

Can someone confirm/deny this?
http://groups.google.com/group/comp.lang.python/browse_thread/thread/4f55b4cb77653115/6543ed65bbb51c09?lnk=gst&q=rusi#6543ed65bbb51c09

http://groups.google.com/group/comp.lang.python/browse_thread/thread/36e757567f28368e/8737ab250b9f657a?lnk=gst&q=rusi+ipython#8737ab250b9f657a
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: and becomes or and or becomes and

2011-05-23 Thread rusi
On May 23, 5:30 am, Steven D'Aprano  wrote:
> On Sun, 22 May 2011 15:39:33 -0700, Tim Roberts wrote:
> > Stef Mientki  wrote:
>
> >>must of us will not use single bits these days, but at first sight, this
> >>looks funny :
>
> > a=2
> > b=6
> > a and b
> >>6
> > a & b
> >>2
> > a or b
> >>2
> > a | b
> >>6
>
> > That IS funny.  Interesting how a careful choice of arugments will fool
> > us. One of my favorite math jokes is like that.  A teacher asked a
> > student to reduce the following fraction:
> >   16
> >  
> >   64
>
> > He says "all I have to do is cancel out the sixes, so the answer is
> > 1/4".
>
> One of my favourite variations on this is by Abbott and Costello, where
> Costello proves that 13*7 = 28 in three different ways.
>
> http://www.youtube.com/watch?v=rLprXHbn19I

Ha Ha! [You're hired Steven]
-- 
http://mail.python.org/mailman/listinfo/python-list


python help

2011-05-23 Thread pablo araya

> > Hi I'm tryin to create a game but I have a question in how to save
> > (saveasfile) the value of a global variable.. and then load the same value
> > with openfile.
> > Also for example you have a main label and a botton on the left so when
> > you click the left bottom the label will change or refresh to another label,
> > and when you return to the original label show or refresh to the original
> > one. All the works is with matrix in python 3.2 and also tkinter.
Thanks!
  -- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-23 Thread John Bokma
Chris Angelico  writes:

> That said, though, I still do not believe in Python's philosophy of
> significant whitespace. I like to be able, if I choose, to put one
> entire "logical unit" on one line, such that it can be commented out
> with a single comment marker, 

Use an editor that can with a single command comment out a selection
(and revert this), like Emacs.


-- 
John Bokma   j3b

Blog: http://johnbokma.com/Perl Consultancy: http://castleamber.com/
Perl for books:http://johnbokma.com/perl/help-in-exchange-for-books.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem in using subprocess module and communicate()

2011-05-23 Thread Tim Golden

[cc-ing back to the list; please keep the conversation over there...]

On 23/05/2011 13:11, vijay swaminathan wrote:

What I want to achieve is, I want to run a batch file on a command prompt.

The reason for using thread is not for running multiple scripts
simultaneously. It is just to monitor my script running in command
prompt. only on closing the command prompt, I like to perform some more
actions. so I look to monitor my thread. Hope it is clear until now.


Ok. That's perfectly clear.



the below mentioned code does not invoke the command prompt at all. Does
the subprocess.call take care of invoking the command prompt?


Adding shell=True invokes %COMSPEC% (usually cmd.exe) under the covers.
How do you know it's not invoking the command prompt? Does your
batch file generate output? And is that output generated? Without
the CREATE_NEW_CONSOLE flag, you won't see an extra box pop up, but
unless you specifically want one, then don't bother.

OK, baby steps. Here's a batch file:


@echo Hello



and here's a Python script which runs it:


import subprocess

subprocess.call ("tjg.bat", shell=True)



I opened a console (cmd.exe), ran tjg.py and, as expected, "Hello"
appears in the same console. Note that, if I hadn't made the .bat
file generate some output I wouldn't have seen anything but it
would still have worked.

I now make the .bat file do something more long-winded, such as
fire up a Python session which waits for five seconds and then
completes:


@echo off
echo Starting
python -c "import time; time.sleep (5)"
echo Finished



When I run tjg.py again, I see "Starting" and then a pause of
5 seconds, and then "Finished".

Now let's make the Python program monitor to see when that batch has 
finished by watching the isAlive status and then sleeping for a second:



import subprocess
import threading
import time

def run_tjg ():
  subprocess.call ("tjg.bat", shell=True)

t = threading.Thread (target=run_tjg)
t.start ()

while t.isAlive ():
  print "is alive"
  time.sleep (1)

print "Thread is complete"



When I run this, I get a mixture of output, depending on what
gets to the console first, but essentially I see the batch file
starting, I get a series of about 5 "is alive" messages, then
the batch file "Finished" message and the Python "Thread is
complete" message.

Does that work for you?

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


Re: Functional Programing: stop using recursion, cons. Use map & vectors

2011-05-23 Thread Pascal J. Bourguignon
torb...@diku.dk (Torben Ægidius Mogensen) writes:

> Xah Lee  writes:
>
>
>> Functional Programing: stop using recursion, cons. Use map & vectors.
>>
>> 〈Guy Steele on Parallel Programing〉
>> http://xahlee.org/comp/Guy_Steele_parallel_computing.html
>
> This is more or less what Backus said in his Turing Award lecture about
> FP.

Stop inflating his ego!  Next he'll quote Nobel prize winners...

-- 
__Pascal Bourguignon__ http://www.informatimago.com/
A bad day in () is better than a good day in {}.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 and timezones

2011-05-23 Thread Miki Tebeka
> [1] http://pypi.python.org/pypi/PosixTimeZone/0.9.4
> [2] http://pypi.python.org/pypi/pytz/2011g
> [3] http://docs.python.org/library/datetime.html#tzinfo-objects
Also 
http://labix.org/python-dateutil#head-587bd3efc48f897f55c179abc520a34330ee0a62

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


Multiple file select with tkFileDialog passes back 'decorated' strings (sometimes)

2011-05-23 Thread Alex van der Spek
I switched from Mark Hammonds pywin32 extensions for file choosers as the 
multiselect there seems to crash on me when selecting more than a few dozen. 
Using Tk now. Works well but the resulting string passed back seems to 
'decorated' when the files are on local disk and not decorated when 
retrieved over a USB interface from an external disk?


I do this:


From local disk I get back:


'{file1.bin} {file2.bin}'


From external disk I get back:


'file1.bin file2.bin'

I can handle/parse both, not an issue but it raises the question: Are these 
the only two possibilities? Is it the same across platforms (I use Python 
2.7 on Win Vista)?


See code below.

Thanks for the insight!
Alex van der Spek
+++

from Tkinter import *
import tkFileDialog as tkf

tkroot=Tk()
tkroot.withdraw()

initdir=os.environ['HOME']
filetype=[('Binary Timeseries','*.bin'),('All files','*.*')]
filenames=tkf.askopenfilenames(parent=tkroot,initialdir=initdir,filetypes=filetype)
tkroot.destroy() 


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


Re: Python 2.6 and timezones

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 10:56 PM, loial  wrote:
> Thanks...but being a python newbie I am struggling to understand how
> to do this.
>
> How can I use tzinfo to do the equivalent of what I do in Java, which
> is  :
>
>TimeZone tz1 = TimeZone.getDefault();
>
>long localOffset = tz1.getOffset(date.getTime());
>
>TimeZone tz2 = TimeZone.getTimeZone("EST");
>
>long remoteOffset = tz2.getOffset(date.getTime());
>

>>> from pytz import timezone, FixedOffset
>>> import time
>>> from datetime import datetime
>>> local_tz = FixedOffset(-time.timezone/60)

time.timezone returns local timezone in seconds and negative sign.
FixedOffset converts it into tzinfo object.

>>> now = datetime.now()
>>> local_tz.utcoffset(now)
datetime.timedelta(0, 36000)

utcoffset() returns timedelta object as offset. It requires datetime
object as first parameter due to weird API of base tzinfo class, but
it is not used in calculation, and you can pass any other object,
including None instead, like `local_tz.utcoffset(None)`

>>> remote_tz = timezone("EST")
>>> remote_tz.utcoffset(now)
datetime.timedelta(-1, 68400)

You can add or substract these timedelta objects directly from
datetime objects or use astimezone():

>>> now = datetime.now(local_tz)
>>> now
datetime.datetime(2011, 5, 23, 22, 41, 48, 398685, tzinfo=pytz.FixedOffset(600))
>>> now.astimezone(remote_tz)
datetime.datetime(2011, 5, 23, 7, 41, 48, 398685, tzinfo=)


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


Re: and becomes or and or becomes and

2011-05-23 Thread Colin J. Williams

On 22-May-11 15:23 PM, Stef Mientki wrote:

hello,

must of us will not use single bits these days,
but at first sight, this looks funny :


a=2
b=6
a and b

6

a&  b

2

a or b

2

a | b

6

cheers,
Stef

5.2. Boolean Operations — and, or, not

These are the Boolean operations, ordered by ascending priority:
  Operation Result  Notes
x or y   if x is false, then y, else x  (1)
   x and y   if x is false, then x, else y  (2)
not xif x is false, then True, else False   (3)

The second line is puzzling at first look, but consistent.

It is analogous to the Conditional Expression.
See: 
http://docs.python.org/reference/expressions.html#conditional-expressions


Colin W.

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


Re: Python 2.6 and timezones

2011-05-23 Thread loial
Thanks...but being a python newbie I am struggling to understand how
to do this.

How can I use tzinfo to do the equivalent of what I do in Java, which
is  :

TimeZone tz1 = TimeZone.getDefault();

long localOffset = tz1.getOffset(date.getTime());

TimeZone tz2 = TimeZone.getTimeZone("EST");

long remoteOffset = tz2.getOffset(date.getTime());

Any help appreciated



On May 23, 11:48 am, Daniel Kluev  wrote:
> On Mon, May 23, 2011 at 9:32 PM, loial  wrote:
> > Does python have an equivalent of the java Timezone object?
>
> > I need to be able to get offsets for timezones (only U.S. time zones
> > at the moment)
>
> Depends on what exactly do you want. If you need to convert timezone
> name into current offset, you should use [1] or [2].
> If you just need to handle known offsets for datetime objects, there
> is tzinfo class in datetime module, [3].
>
> [1]http://pypi.python.org/pypi/PosixTimeZone/0.9.4
> [2]http://pypi.python.org/pypi/pytz/2011g
> [3]http://docs.python.org/library/datetime.html#tzinfo-objects
>
> --
> With best regards,
> Daniel Kluev

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 10:17 PM, Octavian Rasnita  wrote:
> From: "Daniel Kluev" 
> Aha, so with other words that ORM doesn't have that feature.
> DBIX::Class also use the DateTime module, but it can use it directly,
> without needing to write more code for that, and it can also return
> localized dates.

Once again. ORMs return _python builtin type_. Localization is not
their responsibility, and plugging it there is code bloat, rather than
feature. Sure you may ask ORM to handle JSONRPC requests on its own,
but ORM responsibility is to map RDBMS features to language objects.
All good python packages limit their functionality to specific field,
so you could choose one you prefer for each different task
independently.

> without needing to load the DateTime module manually and to initialize the 
> DateTime object manually...

This is basically stating that you didn't read the code I posted.
Where did you ever find "initialize the DateTime object manually"?
Sorry, but its pointless to discuss anything if you don't want to even
read properly examples you receive.


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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Duncan Booth
Ulrich Eckhardt  wrote:

> Ahem, is this Java the language that a certain, well-known service
> provider is getting screwed over hard currently, because they forgot
> to read the fineprint in the declaration of freedom?

That would be the case where the plaintiff has been ordered to drop all but 
3 of their 132 claims? It isn't at all obvious yet who is going to be 
'screwed over hard'.

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Ulrich Eckhardt
Octavian Rasnita wrote:
> Somebody told that C# and Objective C are good languages. They might be
> good, but they are proprietary, and not only that they are proprietary,
> but they need to be ran under platforms that cannot be used freely, so
> from the freedom point of view, Perl, Ruby, Python and Java are the ways
> to go.

Ahem, is this Java the language that a certain, well-known service provider 
is getting screwed over hard currently, because they forgot to read the 
fineprint in the declaration of freedom? And this Objective C, isn't this 
the language that GCC had support for since before it properly supported 
C++, and that on a multitude of targets?

I'm probably just confusedly feeding flames here, but I like it snug and 
warm. (:

Uli

-- 
Domino Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Octavian Rasnita

From: "Daniel Kluev" 
...
Can it also set the current locale, for example romanian, and print the 
name of the current month?

...something like t1.date.set_locale('ro').month_name?


There is separate module for date localization. You can pass datetime
object to it and it will give you needed value.



Aha, so with other words that ORM doesn't have that feature.
DBIX::Class also use the DateTime module, but it can use it directly, 
without needing to write more code for that, and it can also return 
localized dates.



The ones that bash other languages on the mailing list for their prefered 
language should provide good comparisons and not just make false 
statements


That would be valid if I would 'bash other languages', but I just
responded to your claim that Perl has advanced modules which are not



No you haven't responded because you haven't shown any thing that can be 
done by the web framework and the ORM you are praising but can't be done by 
Catalyst and DBIx::Class, however I have shown you that DBIx::Class can 
return DateTime objects directly, without needing to load the DateTime 
module manually and to initialize the DateTime object manually...


And don't take my words out of the context, because I have also answered to 
another list member that was bashing Perl without offering other helpful 
information than just that kind of jokes which are usually made by teenagers 
under 30.


Octavian

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


Re: how to get PID from subprocess library

2011-05-23 Thread TheSaint
GMail Felipe wrote:


> For the "ps" command, have you seen the psuti module?
> 
> The link to it is: http://code.google.com/p/psutil/

You gave a brand new start :)
I bit of additional program to include into the package ;)

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Condition.wait(timeout) oddities

2011-05-23 Thread Floris Bruynooghe
Hi all

I'm a little confused about the corner cases of Condition.wait() with a timeout 
parameter in the threading module.

When looking at the code the first thing that I don't quite get is that the 
timeout should never work as far as I understand it.  .wait() always needs to 
return while holding the lock, therefore it does an .acquire() on the lock in a 
finally clause.  Thus pretty much ignoring the timeout value.

The second issue is that while looking around for this I found two bug reports: 
http://bugs.python.org/issue1175933 and http://bugs.python.org/issue10218.  
Both are proposing to add a return value indicating whether the .wait() timed 
out or not similar to the other .wait() methods in threading.  However the 
first was rejected after some (seemingly inconclusive) discussion.  While the 
latter had minimal discussion and and was accepted without reference to the 
earlier attempt.  Not sure if this was a process oversight or what, but it does 
leave the situation confusing.

But regardless I don't understand how the return value can be used currently: 
yes you did time out but you're still promised to hold the lock thanks to the 
.acquire() call on the lock in the finally block.

In my small brain I just can't figure out how Condition.wait() can both respect 
a timeout parameter and the promise to hold the lock on return.  It seems to me 
that the only way to handle the timeout is to raise an exception rather then 
return a value because when you get an exception you can break the promise of 
holding the lock.

But maybe I'm missing something important or obvious, so I'd be happy to be 
enlightened!

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


Re: Python 2.6 and timezones

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 9:32 PM, loial  wrote:
> Does python have an equivalent of the java Timezone object?
>
> I need to be able to get offsets for timezones (only U.S. time zones
> at the moment)

Depends on what exactly do you want. If you need to convert timezone
name into current offset, you should use [1] or [2].
If you just need to handle known offsets for datetime objects, there
is tzinfo class in datetime module, [3].


[1] http://pypi.python.org/pypi/PosixTimeZone/0.9.4
[2] http://pypi.python.org/pypi/pytz/2011g
[3] http://docs.python.org/library/datetime.html#tzinfo-objects

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


Re: Abandoning Python

2011-05-23 Thread Robin Becker

On 21/05/2011 16:49, John J Lee wrote:



I still like Python after using it for over a decade, but there are
things I don't like.

..
a relatively new one that's going about is cobra, http://cobra-language.com/, it 
appears to have some of the features you indicate eg speed, some kind of 
interfaces (contracts I think), but it needs net or mono.

--
Robin Becker

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


Re: Dealing with name clashes in pypi

2011-05-23 Thread Patrick Sabin

On 2011-05-22 23:23, Terry Reedy wrote:

On 5/22/2011 2:34 PM, Patrick Sabin wrote:

I wanted to register my project (epdb) in pypi. Unfortunately there
already exists a project with the same name. It is not possible for me
to change the name of the project, because I used it in multiple
writings. Any ideas how I can deal with the situation? Is it possible to
register a project under a different name in pypi than the actual
project name?


I presume so. How would pypi know the 'actual' name?
However, there is a catalog sig list (mirrored as
gmane.comp.python.catalog) where you might get specific suggestions on
how to handle this.



Thanks for the tip. I will try it there.

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


Python 2.6 and timezones

2011-05-23 Thread loial
Does python have an equivalent of the java Timezone object?

I need to be able to get offsets for timezones (only U.S. time zones
at the moment)



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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 8:41 PM, Octavian Rasnita  wrote:
> From: "Daniel Kluev" 
> As I said, that ORM is not able to do those SQL constructs without using
> literal SQL code, but only Python variables and data structures...
> An ORM is usually prefered exactly because it doesn't force the programmer
> to concatenate strings for generating the SQL code, but he/she can use just
> standard Perl/Python code.
> Or this is possible in another way without using SQL code?

Did you actually read the code? SQL there is debug output of
SQLAlchemy for python code `Session.query(Test).from_self().all()`, I
left it there to just show you that it emits subquery to RDBMS.
All code in REPL is prefixed by `>>> `. Other lines are just output.

> Can it also set the current locale, for example romanian, and print the name 
> of the current month?
> ...something like t1.date.set_locale('ro').month_name?

There is separate module for date localization. You can pass datetime
object to it and it will give you needed value.

> The ones that bash other languages on the mailing list for their prefered 
> language should provide good comparisons and not just make false statements

That would be valid if I would 'bash other languages', but I just
responded to your claim that Perl has advanced modules which are not
available for Python, esp. in web frameworks, as I find it one of
areas where Python shines most.
Sure Python has drawbacks, esp. its performance and poor threads
support (GIL), but flexibility and modules of all flavors and types
are not among them. Introduction of parameter annotations should make
these modules even greater, once python 3.x is widely adopted.

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


Re: Multiprocessing: don't push the pedal to the metal?

2011-05-23 Thread Adam Tauno Williams
On Mon, 2011-05-23 at 10:32 +1000, Chris Angelico wrote:
> On Mon, May 23, 2011 at 7:06 AM, John Ladasky  wrote:
> > If I spawn N worker sub-processes, my application in fact has N+1
> > processes in all, because there's also the master process itself.
> > I'd still appreciate hearing from anyone else who has more experience
> > with multiprocessing.  If there are general rules about how to do this
> > best, I haven't seen them posted anywhere.  This may not be a Python-
> > specific issue, of course.
> I don't have much experience with Python's multiprocessing model, but
> I've done concurrent programming on a variety of platforms, and there
> are some common issues.

I develop an app that uses multiprocessing heavily.  Remember that all
these processes are processes - so you can use all the OS facilities
regarding processes on them.  This includes setting nice values,
schedular options, CPU pinning, etc...

> Each CPU (or core) has its own execution cache. If you can keep one
> thread running on the same core all the time, it will benefit more
> from that cache than if it has to keep flitting from one to another.

+1

> You undoubtedly will have other processes in the system, too. As well
> as your master, there'll be processes over which you have no control
> (unless you're on a bare-bones system). Some of them may preempt your
> processes.

This is very true.  You get a benefit from dividing work up to the
correct number of processes - but too many processes will quickly take
back all the benefit.  One good trick is to have the parent monitor the
load average and only spawn additional workers when that value is below
a certain value.

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 7:49 PM, Octavian Rasnita  wrote:
> That is not an array, but a list. An array has a name and we can't do
> something like the following simple statement in Python:
>
> l = (1, 2)
> d = dict(l)

> An array has a name
What?
In python there is no difference whether your object has any names
mapped to it or not. Its all the same, and object itself does not even
know.
Moreover, (1, 2) is tuple rather than 'array'. If you mean array as
implemented as array, then list is what you want. If you mean array
literally, there is special type 'array' somewhere in stdlib.

As for "can't do":

>>> a = [1,2]
>>> dict([a])
{1: 2}
>>> a = (1,2)
>>> dict([a])
{1: 2}


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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Octavian Rasnita

From: "Daniel Kluev" 

On Mon, May 23, 2011 at 5:06 PM, Octavian Rasnita  
wrote:

There are more, but a single eloquent feature is the possibility of
interpreting variables in strings which cannot be done so nice in Python.


I've should probably mentioned it earlier, but I'm not Perl expert,
not following its development and can't be bothered to read its docs.
Could you please provide examples of features you mention with
expected result, so I could suggest reasonable Python analogue?


The ones that bash other languages on the mailing list for their prefered 
language should provide good comparisons and not just make false statements, 
considering that it is enough, since most of the list members will agree 
because they like Python more than other languages anyway.


If they think that what they say is true, why don't they make those 
statements on Perl mailing lists, but again, offering valid comparisons.



But if you want to couple it with controller code, there, as I said,
are numerous ways to do it. You can even do something like this:

class SomeController(BaseController):
   ...
   @map(conditions=dict(method='GET'))
   def some_method(self, arg1:int, arg2:str):
...
so it would be called via /somecontroller/some-method/1/blabla with
trivial decorator.



Is the url something like /some_controller/some_method? Or the underlines 
are deleted from the name of the controller and replaced with "-" in the 
name of the method?
Is it possible to also add a configuration here to call this some_method 
when the url /some_controller/some-method-string is accessed?

(define another string than the name of the method)
Is it possible to configure it to access this subroutine only if a certain 
number of parameters are sent in the URL?


If yes, it means that its dispatcher is better than I've seen in the short 
tutorial on the web.


(unless in Pylons/Pyramid can be also defined chained mappings and 
mappings

based on regular expressions).


Not sure what do you mean by "based on regular expressions". Routes
paths ARE regular expressions. Conditions are regexes too.

As for chained mappings - no idea, never had the need in such thing.


The chained dispatcher is one of the best thing offered by Catalyst, because 
with it the same code should not be used twice.


For example, one can define a subroutine in which a certain record is 
selected from the DB and is placed in stash.
Then there may be other subroutines for different tasks, one for editing 
that record, one for deleting that record and so on.
One chain can start with the base subroutine that makes the selection from 
the DB then executes the subroutine that makes the deletion and another 
chain can start with the base subroutine that makes the selection than 
continues with the one that starts the editting.
Of course, the chain can have more links, not only 2, but this was just a 
very short example.


I've checked the documentation for some of them and I've seen that most 
of
them don't support sub-selects and some of them require using plain SQL 
code

in their construct for more complex queries.
Please tell me which of them supports sub-selects, and are able to return
objects for date and datetime fields that have methods for beeing able to
print just the year or day, or the months names in the specified locale
because it would be useful.


Python has builtin type for DateTime, and SQLAlchemy, for example,
returns exactly that:

t1.date.month

5


Can it also set the current locale, for example romanian, and print the name 
of the current month?

...something like t1.date.set_locale('ro').month_name?


SELECT anon_1.test_id AS anon_1_test_id, anon_1.test_val AS
anon_1_test_val, anon_1.test_date AS anon_1_test_date
FROM (SELECT test.id AS test_id, test.val AS test_val, test.date AS 
test_date

FROM test) AS anon_1


As I said, that ORM is not able to do those SQL constructs without using 
literal SQL code, but only Python variables and data structures...
An ORM is usually prefered exactly because it doesn't force the programmer 
to concatenate strings for generating the SQL code, but he/she can use just 
standard Perl/Python code.

Or this is possible in another way without using SQL code?

it can do but DBIx::Class cannot, because otherwise it would be very 
simple

for anyone to just say "go to read the documentation and see how great it
is".


But "go to read the docs" argument works both ways - I have zero
knowledge of DBIx::Class, so obviously I cannot say what features it
lacks compared to SQLA.


Yes you are perfectly right, but not those programmers that also use Perl 
started to say that Perl can do this and Python can't, or that in Perl this 
is shorter and nicer than in Python.
I just wanted to show that anything Python can do can be done in Perl also, 
and in some fields Python is better, in other fields Perl is better, and we 
should use whatever we like the most, and not say bad words about other 
languages or about those who

Re: Why did Quora choose Python for its development?

2011-05-23 Thread Octavian Rasnita

From: "Chris Angelico" 
On Mon, May 23, 2011 at 3:31 PM, Octavian Rasnita  
wrote:

From: "Dennis Lee Bieber" 


Since indentation seems so crucial to easy comprehension of the logical
structure of a program,
making it a mandatory syntactical structure becomes a desirable feature
for code that must be maintained (by others, in many cases).


Why "in many cases"? I wrote hundreads of programs which are working fine
and which are maintained only by me. (But they would be very easy to
maintain by other people if it would be necessary).
So in that case, why to be forced to use a strict indentation?


The reason for clear code is maintenance, not maintenance-by-others.
If you come back to something in a year, you'll appreciate proper
variable names, indentation, etc.

That said, though, I still do not believe in Python's philosophy of
significant whitespace. I like to be able, if I choose, to put one
entire "logical unit" on one line, such that it can be commented out
with a single comment marker, or duplicated to another line and one
copy commented out, or whatever. To that end, I sometimes want to put
an if, its associated else, and sometimes a statement for both
branches, all in the one line. And that's not possible when whitespace
alone defines the end of an if/else block (the one-line form of a
Python 'if' can't have a non-conditional statement after it at all),
but is quite easy when things are delimited with braces.



Yes I also agree with that, and I also prefer *in some cases* to write short 
code in a single line like:


print "..." if $var;

print $var == 123 ? "abcd" : "cedf";

print $var =~ /foo/ ? "abc" : "cdef";

...instead of writing a few lines of code. These constructs are not 
recommended for Perl either, and Perl::Critic would give a warning when it 
will be used with a certain level of errors checking, but it is preferable 
to be able to do what you want how you or your team want, not as the creator 
of the programming language wants.


And I don't think that there are programmers that find the lines above hard 
to understand or maintain.


Octavian

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Octavian Rasnita

From: "Terry Reedy" 

On 5/23/2011 1:31 AM, Octavian Rasnita wrote:



I am talking about a simple way of creating a hash/dict from an array,
which is so simple that there should be really a single way to do it, or
very few.


Again, Python has such:

>>> dict([['one',1],['two', 2]])
{'two': 2, 'one': 1}



That is not an array, but a list. An array has a name and we can't do 
something like the following simple statement in Python:


l = (1, 2)
d = dict(l)

While in Perl we can do:

@l = (1, 2);
%d = @l;

But let's remember from what this discussion started. This is not a Python 
critique, because each language has its own ways.
I just wanted to show that the fact that "there is more than one way to do 
it" in Perl and that "there is a single way" in Python are just buzzwords, 
because this was an example where in Python there are many ways to do it 
while in Perl there is a single way used usually, which is also more simple.


Octavian

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


ANN: eGenix mx Base Distribution 3.2.0 (mxDateTime, mxTextTools, etc.)

2011-05-23 Thread eGenix Team: M.-A. Lemburg


ANNOUNCING

   eGenix.com mx Base Distribution

  Version 3.2.0 for Python 2.4 - 2.7

   Open Source Python extensions providing
 important and useful services
for Python programmers.

This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-mx-Base-Distribution-3.2.0-GA.html



ABOUT

The eGenix.com mx Base Distribution for Python is a collection of
professional quality software tools which enhance Python's usability
in many important areas such as fast text searching, date/time
processing and high speed data types.

The tools have a proven record of being portable across many Unix and
Windows platforms. You can write applications which use the tools on
Windows and then run them on Unix platforms without change due to the
consistent platform independent interfaces.

Contents of the distribution:

 * mxDateTime - Easy to use Date/Time Library for Python
 * mxTextTools - Fast Text Parsing and Processing Tools for Python
 * mxProxy - Object Access Control for Python
 * mxBeeBase - On-disk B+Tree Based Database Kit for Python
 * mxURL - Flexible URL Data-Type for Python
 * mxUID - Fast Universal Identifiers for Python
 * mxStack - Fast and Memory-Efficient Stack Type for Python
 * mxQueue - Fast and Memory-Efficient Queue Type for Python
 * mxTools - Fast Everyday Helpers for Python

All available packages have proven their stability and usefulness in
many mission critical applications and various commercial settings all
around the world.

For more information, please see the distribution page:

http://www.egenix.com/products/python/mxBase/



NEWS

The 3.1.3 release of the eGenix mx Base Distribution is the latest
release of our open-source Python extensions.

The new version provides major enhancements of the included
packages. To highlight a few:

 * Added support for Python 2.7 on all supported platforms.
 * Added native Window x64 support.

 * Included many news features in mxDateTime to enhance
   interoperability with Python's datetime module and to increase
   overall performance:

   o Mixed type support to allow operations between mxDateTime objects
 and Python's datetime module

   o New constructor methods on the objects to easily switch from
 mxDateTime objects to datetime module objects.

   o New constructor support to easily switch back from datetime
 module objects to mxDateTime objects

 * Added new mx.Misc.Daemon module which provides abstractions to
   implement Unix daemon processes.

 * Added code cleanups and switched to Python's own memory allocator,
   which results in performance enhancements across all subpackages.

 * Added back easy_install support and included pip support.

As always, we are providing pre-built binaries for all common
platforms: Windows 32/64-bit, Linux 32/64-bit, FreeBSD 32/64-bit, Mac
OS X 32/64-bit. Source code archives are available for installation on
all other Python platforms, such as Solaris, AIX, HP-UX, etc.

To simplify installation in Zope/Plone and other egg-based systems, we
have also precompiled egg distributions for all platforms. These are
available on our own PyPI-style index server for easy and automatic
download.

Whether you are using a pre-built package or the source distribution,
installation is a simple "python setup.py install" command in all
cases. The only difference is that the pre-built packages do not
require a compiler or the Python development packages to be installed.

For a list of changes, please refer to the eGenix mx Base Distribution
change log at

http://www.egenix.com/products/python/mxBase/changelog.html

and the change logs of the various included Python packages.



DOWNLOADS

The download archives and instructions for installing the packages can
be found on the eGenix mx Base Distribution page:

http://www.egenix.com/products/python/mxBase/



LICENSE

The eGenix mx Base package is distributed under the eGenix.com Public
License 1.1.0 which is an Open Source license similar to the Python
license. You can use the packages in both commercial and non-commercial
settings without fee or charge.

The package comes with full source code



SUPPORT

Commercial support for this product is available from eGenix.com.
Please see

http://www.egenix.com/services/support/

for details about our support offerings.

Enjoy,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, May 23 2011)
>>> Python/Zo

Re: Why did Quora choose Python for its development?

2011-05-23 Thread Aleksandar Radulovic
Hi,

I'm going to skip the Perl vs. Python flame-bait and correct your one statement.

On Sun, May 22, 2011 at 7:44 AM, Octavian Rasnita  wrote:
> Somebody told that C# and Objective C are good languages. They might be good, 
> but they are proprietary, and not only that they are proprietary, but they 
> need to be ran under platforms that cannot be used freely, so from the 
> freedom point of view, Perl, Ruby, Python and Java are the ways to go.

Neither of those are proprietary and can, in fact, be used freely. GNU
compiler compiles objective-c code with no problem and then there's
Mono for C# and .NET development on multiple platforms.

But if by proprietary you mean the libraries and APIs that complement
those languages, the it's worth noting that Mono implements most of
.NET framework and it is free. If you want "free" Cocoa APIs (or other
Obj-C frameworks) look into GnuSTEP.

Best regards,
alex.



-- 
a lex 13 x
http://www.a13x.info
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem in using subprocess module and communicate()

2011-05-23 Thread Tim Golden

On 21/05/2011 16:56, vijay swaminathan wrote:

I'm having some problem in using the communicate() along with the
subprocess.I would like to invoke a command prompt and pass  on a .bat
file to execute. I went through the subprocess module and understood
that using communicate, we can send the send data to stdin.


I'm afraid you're running the risk of giving us too little information
here, Vijay. You've pointed to the docs you've read and provided code,
which is A Good Thing. Unfortunately, the code you've provided is
clearly not what you'll ultimately be running (unless you're in the
game for a convoluted means of getting a directory listing) and, as
Chris touched on in his response, is probably not even what you're
running now, as you're passing the wrong kind of "/k" to cmd.exe.

OK, let's see if I've understood correctly from this and from your
previous posts:

* You have a set of batch scripts you want to launch from Python

* You want to launch them in parallel (possibly different scripts, not 
sure) so you're setting up threads.


You seem to be trying to meet these requirements by opening a
command shell with an arbitrary command, leaving it open and
feeding its stdin with the batch script name so that it runs,
and then polling it until it finishes.

In short, you're making a mountain out of a molehill. If you
need to run batch scripts from a command shell, then use
subprocess.call with the name of the batch script and shell=True
(the last isn't always necessary; it seems to depend on the
C runtime, but it won't harm to have it there):


import subprocess

result = subprocess.call ("name-of-script.bat", shell=True)



If you want to run that in a thread:


import subprocess
import threading

def run_script (path_to_script):
  subprocess.call (path_to_script, shell=True)

t = threading.Thread (target=run_script, args=("name-of-script.bat,"))
t.start ()

while True:
  # do stuff
  if t.isAlive ():
print "still running"



You might, as you have above, want to launch a new console with each
subprocess or the output could get quite messy. There are lots of
variations on this theme: you could use a Queue to get the success or
failure back from the threads.

It's not clear whether you actually need to feed input into your
batch scripts, as the only reason you're using .communicate above
is to actually *run* the batch scripts.

I could go on guessing what your use-case is, assuming that it doesn't
involve a command shell with the output from a "dir" command, but it'll
be easier if you can describe how closely what I've written above
matches your need.

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Daniel Kluev
On Mon, May 23, 2011 at 5:06 PM, Octavian Rasnita  wrote:
> There are more, but a single eloquent feature is the possibility of
> interpreting variables in strings which cannot be done so nice in Python.

I've should probably mentioned it earlier, but I'm not Perl expert,
not following its development and can't be bothered to read its docs.
Could you please provide examples of features you mention with
expected result, so I could suggest reasonable Python analogue?

> This is false. Explicit in this case means to write code in 2 places for
> doing a certain thing, and maintaining means changing the code in 2 places,
> which is harder and prone to errors.

Not sure what do you mean by 'write code in 2 places'. All mapping
code is located in routes config, including all needed args
validation.
But if you want to couple it with controller code, there, as I said,
are numerous ways to do it. You can even do something like this:

class SomeController(BaseController):
...
@map(conditions=dict(method='GET'))
def some_method(self, arg1:int, arg2:str):
 ...

so it would be called via /somecontroller/some-method/1/blabla with
trivial decorator.

> (unless in Pylons/Pyramid can be also defined chained mappings and mappings
> based on regular expressions).

Not sure what do you mean by "based on regular expressions". Routes
paths ARE regular expressions. Conditions are regexes too.

As for chained mappings - no idea, never had the need in such thing.

> Yes, the single difference is that Catalyst supports all of them, and it
> also supports using any templating system, and any ORM and any form
> processor, while some of the Python web frameworks don't support absolutely
> everything and you need to abandon some preferred modules for beeing able to
> use some other modules which are supported.

Pyramid and Pylons let you use pretty much any templating package and
ORM as well. There is nothing in them that would block such modules.

> I've checked the documentation for some of them and I've seen that most of
> them don't support sub-selects and some of them require using plain SQL code
> in their construct for more complex queries.
> Please tell me which of them supports sub-selects, and are able to return
> objects for date and datetime fields that have methods for beeing able to
> print just the year or day, or the months names in the specified locale
> because it would be useful.

Python has builtin type for DateTime, and SQLAlchemy, for example,
returns exactly that:

#> python
Python 2.7.1 (r271:86832, May 17 2011, 19:31:41)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sadt import Test, Session
>>> import datetime
>>> Test(1)

>>> Test(2)

>>> t1 = Session.query(Test).filter(Test.val == 1).one()
>>> t1

>>> t1.date
datetime.datetime(2011, 5, 23, 18, 53, 39, 459054)
>>> t1.date.year
2011
>>> t1.date.month
5
>>> print Session.query(Test).filter(Test.date == datetime.datetime(2011, 5, 
>>> 23, 18, 53, 39, 459054)).one()

>>> print Session.query(Test).filter(Test.date > datetime.date(2010, 1, 
>>> 1)).all()
[, ]

sadt sources here if interesting: http://pastebin.ca/2067372

So as you see, datetime is not only returned properly, but you can
also do queries with either date or datetime values, including
comparison and range.

Subqueries are fully supported too:
>>> ...
>>> Session.query(Test).from_self().all()
2011-05-23 19:07:02,662 INFO sqlalchemy.engine.base.Engine.0x...552c
SELECT anon_1.test_id AS anon_1_test_id, anon_1.test_val AS
anon_1_test_val, anon_1.test_date AS anon_1_test_date
FROM (SELECT test.id AS test_id, test.val AS test_val, test.date AS test_date
FROM test) AS anon_1
2011-05-23 19:07:02,662 INFO sqlalchemy.engine.base.Engine.0x...552c ()
[, , , , ]

This is most trivial example of subqueries, since I'm too lazy to
produce proper tables to demonstrate it, but SQLAlchemy has very good
subquery support, as its typical way to deal with one-to-many
relations (but it does support other loading strategies as well,
including inner/outer joins or lazy loading).

> it can do but DBIx::Class cannot, because otherwise it would be very simple
> for anyone to just say "go to read the documentation and see how great it
> is".

But "go to read the docs" argument works both ways - I have zero
knowledge of DBIx::Class, so obviously I cannot say what features it
lacks compared to SQLA.
However this is what I wanted to highlight - you cannot simply state
that "Perl offers more advanced modules and libraries which are not
available for Python" if you don't have reasonable experience with
according Python modules.


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


Re: Functional Programing: stop using recursion, cons. Use map & vectors

2011-05-23 Thread asandroq
On May 23, 4:29 am, Deeyana  wrote:
>
> You might be interested in Clojure, then. Lists are more abstracted, like
> in Scheme, and vectors and also dictionaries/maps and sets are first
> class citizens along side lists. And unlike Scheme, Clojure has good
> library/host interop support. You can write real-world applications in it
> without spontaneously combusting.

 Nonsense. Several Scheme systems have excellent FFIs with more
than "good library/host interop support".

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


Re: Why did Quora choose Python for its development?

2011-05-23 Thread Chris Angelico
On Mon, May 23, 2011 at 4:46 PM, Carl Banks  wrote:
> On Sunday, May 22, 2011 12:44:18 AM UTC-7, Octavian Rasnita wrote:
>> If Python would be so great, you wouldn't talk so much about how bad are
>> other languages,
>
> Sure we would.  Sometimes it's fun to sit on your lofty throne and scoff at 
> the peasantry.

It's also fun, and sometimes productive, to sit on many different
lofty thrones, and then to have a Jedi Council meeting in which we
discuss which thrones are hard to climb onto, which ones are easy for
a child to sit on but hard to get any work done on, and which ones are
really comfortable and ergonomic, but have just that one little hard
bit to the right of where your arm wants to rest, but if you're
careful it won't jab into you too badly... and in those discussions,
Perl is a literal Swiss Army Knife. :)

> I would suggest that envy isn't the reason, the reason is that Perl is just 
> that much worse than Visual Basic, Pascal, and Delphi.  We only make fun of 
> the really, really bad langauges.

I'm not sure that Perl deserves to be put alongside Visual Basic. I'm
not sure that ANY language deserves that...

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


Re: Abandoning Python

2011-05-23 Thread Chris Angelico
On Mon, May 23, 2011 at 4:33 PM, Steven D'Aprano
 wrote:
> And presumably anyone who has played around with GUI programming in
> Python will have run into message oriented coding.
>

GUI code almost always involves a main loop somewhere that consists of:

while not time_to_terminate:
 get_message()
 dispatch_message()

Voila, you've just implemented message-oriented code in an imperative
way. Doesn't make the language inherently message-oriented. If you're
going to read someone else's code, then, you not only need to know the
language, you need to know the environment in which it runs. I found
that out the hard way when I tried to read some PHP code that was
designed to run inside Joomla - it's quite quite different from
standalone PHP.

I believe assembly language offers as many
paradigms as anything else you might want. With judicious use of
constructs like the Intel "JMP [BP+SI]" and a nice table of jump
targets, you could do message passing, OOP/inheritance, procedures,
and next-programmer-brain-destruction, and hey, it's tabular
too!

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