Re: Logic operators with in statement

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 6:02 AM, Mr.SpOOn mr.spoo...@gmail.com wrote:
 Hi,
 I'm trying to use logical operators (or, and) with the in statement,
 but I'm having some problems to understand their behavior.

 In [1]: l = ['3', 'no3', 'b3']

 In [2]: '3' in l
 Out[2]: True

 In [3]: '3' and '4' in l
 Out[3]: False

 In [4]: '3' and 'no3' in l
 Out[4]: True

 This seems to work as I expected.

No, it doesn't. You are misinterpreting. Membership tests via `in` do
NOT distribute over `and` and `or`.

'3' and '4' in l
is equivalent to:
('3') and ('4' in l)

Recall that non-empty sequences and containers are conventionally True
in Python, so your expression is logically equivalent to:
'4' in l
With '3' not being checked for membership at all.

To check multiple items for membership in a contains, you must write
each `in` test separately and then conjoin then by the appropriate
boolean operator:

'3' in l and '4' in l

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


Re: Logic operators with in statement

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 6:08 AM, Mr.SpOOn mr.spoo...@gmail.com wrote:
 Sorry for replying to myself, but I think I understood why I was wrong.

 The correct statement should be something like this:

 In [13]: ('b3' and '5') in l or ('3' and 'b3') in l
 Out[13]: True

No, you've just run into another misunderstanding.

Given the expression `X and Y`:
If bool(X) is False, it evaluates to X.
Otherwise, it evaluates to Y.

In other words, the subexpression which ends up determining the truth
of the conjunction is what the conjunction evaluates to. `or` works
similarly.
This allows for tricky tricks like:
foo = possiblyFalse or default # use default if given value is false

Thus, due to the parentheses, your expression is equivalent to:
'5' in l or 'b3' in l
Which I trust is not what you intended.

Again, you need to write separate `in`s for each item you need to
check the membership of:
('b3' in l and '5' in l) or ('3' in l and 'b3' in l)

Cheers,
Chris
--
Python language lawyer at your service
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Logic operators with in statement

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 6:23 AM, Xavier Ho cont...@xavierho.com wrote:
snip
 '3' in l and 'no3' in l
 True

 AND operator has a higher precedence, so you don't need any brackets here, I
 think. But anyway, you have to use it like that. So that's something you'll
 have to fix first.

Er, you mean lower precedence. Higher precedence means it would bind
tighter, thus the expression would mean:
'3' in (l and 'no3') in l
which is certainly incorrect.

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


Re: Language mavens: Is there a programming with if then else ENDIF syntax?

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 8:54 AM, Steve Ferg
steve.ferg.bitbuc...@gmail.com wrote:
 This is a question for the language mavens that I know hang out here.
 It is not Python related, except that recent comparisons of Python to
 Google's new Go language brought it to mind.

 NOTE that this is *not* a suggestion to change Python.  I like Python
 just the way it is.  I'm just curious about language design.

 For a long time I've wondered why languages still use blocks
 (delimited by do/end, begin/end, { } , etc.) in ifThenElse statements.

 I've often thought that a language with this kind of block-free syntax
 would be nice and intuitive:

    if condition then
        do stuff
    elif condition then
        do stuff
    else
        do stuff
    endif

 Note that you do not need block delimiters.
snip
 Does anybody know a language with this kind of syntax for
 ifThenElseEndif?

Ruby:

if count  10
  puts Try again
elsif tries == 3
  puts You lose
else
  puts Enter a number
end

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


Re: Web servers

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 11:17 AM, Virgil Stokes v...@it.uu.se wrote:
 Any suggestions on using Python to connect to Web servers (e.g. to access
 financial time series data)?

In what format? Using what protocol?
(*Insert other basic questions that need answering in order to answer
your question here*)

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


Re: Changing the current directory (full post)

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 11:36 AM, vsoler vicente.so...@gmail.com wrote:
 On Nov 16, 2:35 am, Gabriel Genellina gagsl-...@yahoo.com.ar
 wrote:
 En Sun, 15 Nov 2009 09:04:06 -0300, vsoler vicente.so...@gmail.com
 escribió:

  Ever since I installed my Python 2.6 interpreter (I use IDLE), I've
  been saving my
  *.py files in the C:\Program Files\Python26 directory, which is the
  default directory for such files in my system.

  However, I have realised that the above is not the best practice.
  Therefore I created the C:\Program Files\Python26\test directory and I
  want it to be my default directory for saving *.py files, importing
  modules, etc.

 This is *not* a good place either. Non-privileged users should not have
 write permission in the C:\Program Files directory.

  I'd like to do something like the DOS equivalent of   CD test but I
  do not know kow to do it.

  I am currently doing something really awful: I open a *.py file in the
  test subdirectory, I run it with the F5 key and it works! but I am
  doing really something stupid.

 it works! What's the problem then?

  How should I proceed, if I want to proceed properly?

 Sorry but I don't even see your problem. You can save your .py files
 anywhere you like...

 --
 Gabriel Genellina

 Gabriel,

 When I enter IDLE, I'd like to say at the prompt: my current
 directory is...  ...test and then be able to run a module in that
 directory. This is what my problem is!!!

1. File - Open
2. Navigate to file and choose it
3. Press F5

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


Re: Changing the current directory (full post)

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 11:56 AM, vsoler vicente.so...@gmail.com wrote:
 On Nov 16, 8:45 pm, Chris Rebert c...@rebertia.com wrote:
 On Mon, Nov 16, 2009 at 11:36 AM, vsoler vicente.so...@gmail.com wrote:
  On Nov 16, 2:35 am, Gabriel Genellina gagsl-...@yahoo.com.ar
  wrote:
  En Sun, 15 Nov 2009 09:04:06 -0300, vsoler vicente.so...@gmail.com
  escribió:

   Ever since I installed my Python 2.6 interpreter (I use IDLE), I've
   been saving my
   *.py files in the C:\Program Files\Python26 directory, which is the
   default directory for such files in my system.

   However, I have realised that the above is not the best practice.
   Therefore I created the C:\Program Files\Python26\test directory and I
   want it to be my default directory for saving *.py files, importing
   modules, etc.

  This is *not* a good place either. Non-privileged users should not have
  write permission in the C:\Program Files directory.

   I'd like to do something like the DOS equivalent of   CD test but I
   do not know kow to do it.

   I am currently doing something really awful: I open a *.py file in the
   test subdirectory, I run it with the F5 key and it works! but I am
   doing really something stupid.

  it works! What's the problem then?

   How should I proceed, if I want to proceed properly?

  Sorry but I don't even see your problem. You can save your .py files
  anywhere you like...

  When I enter IDLE, I'd like to say at the prompt: my current
  directory is...  ...test and then be able to run a module in that
  directory. This is what my problem is!!!

 1. File - Open
 2. Navigate to file and choose it
 3. Press F5

 Say that you wanted to import a file in the test directory after just
 entering IDLE. How would you do it?

import sys
sys.path.insert(0, C:/path/to/test/dir/here)
import something_in_test_dir

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


Re: faster than list.extend()

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 2:30 PM, Hyunchul Kim
hyunchul.mail...@gmail.com wrote:
 Hi, all.

 I want to improve speed of following simple function.
 Any suggestion?

 **
 def triple(inputlist):
   results = []
   for x in inputlist:
     results.extend([x,x,x])
   return results
 **

You'd probably be better off calling .append() 3 times instead of
.extend() as it would avoid the creation of all those intermediate
3-element lists.

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


Re: Get attribute this way

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 10:04 PM, King animator...@gmail.com wrote:
 Python's getattr, setattr and __getattribute__ commands works fine
 with python types.
 For example:
 print o.__getattribute__(name)
 print getattr(o, name)
 This is the easiest way to get an attribute using a string.

 In my case the Node class load/creates all the attributes from a xml
 file.
 Example
 Input name=position type=float value=0.5/
 Input name=color type=color value=0,0,0/

 There are certain atrributes of compound type.
 Example:
 # Array of colors, Here we are referring first color and second element
 (green)
 self.gradient.colors[0][1] = 0.5
 # Array of floats, referring first element
 self.gradient.positions[0] = 1.0

 Color, color array and floats are all custom classes.

 Now question is how to get these compound attributes using string as
 we do with default singular attributes.
 Example:
 getattr(o, gradient.colors[0][1] )
 I need this to save the data of nodes-attributes into a custom xml
 format, when loading this data back, I create the node first and then
 setup values from the saved xml file.

Can't you just iterate over the data structure? I'm not seeing why
you'd need to use getattr() and friends in the first place.

for color in self.gradient.colors:
for element in color:
#output XML fragment

#repeat for self.gradient.positions, etc.

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


Re: Get attribute this way

2009-11-16 Thread Chris Rebert
On Mon, Nov 16, 2009 at 10:53 PM, King animator...@gmail.com wrote:
 Writing/Reading data to xml is not a problem. The problem is when I
 have to write to attributes in xml, where a connections has been
 established.
 XML:
 Connection sourceattribute=node1.gradient.colors[0][1]
 destattribute=node2.gradient.colors[1][2]/

You did not include an example like this in your original post.

I'd say you're stuck using eval() unless you want to change your
format or write a parser for the subset of Python involved.

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


Re: Accessing a Web server --- how?

2009-11-17 Thread Chris Rebert
On Mon, Nov 16, 2009 at 2:14 AM, Virgil Stokes v...@it.uu.se wrote:
 If one goes to the following URL:
 http://www.nordea.se/Privat/Spara%2boch%2bplacera/Strukturerade%2bprodukter/Aktieobligation%2bNr%2b99%2bEuropa%2bAlfa/973822.html

 it contains a link (click on Current courses NBD AT99 3113A) to:
 http://service.nordea.com/nordea-openpages/six.action?target=/nordea.public/bond/nordeabond.pagemagic=%28cc+%28detail+%28tsid+310746%29%29%29;

 and if you now click on the tab labeled history and compare this will take
 you to:
 http://service.nordea.com/nordea-openpages/six.action?target=/nordea.public/bond/nordeabond.pagemagic=%28cc+%28detail+%28tsid+310746%29+%28view+hist%29%29%29;

 Finally...This is where I would like to connect to the data on a daily
 basis or to gather data over different time intervals. I believe that if I
 can get some help on this, then I will be able to customize the code as
 needed for my own purposes.

HTML parsing: http://www.crummy.com/software/BeautifulSoup/
Downloading webpages: http://docs.python.org/library/urllib.html#urllib.urlopen

BeautifulSoup is excellently documented:
http://www.crummy.com/software/BeautifulSoup/documentation.html
You'll probably be interested in the sections on searching and
navigating the parse tree.

Cheers,
Chris
--
IANAL and do not condone violating website TOSes
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TODO and FIXME tags

2009-11-17 Thread Chris Rebert
2009/11/16 Yasser Almeida Hernández pedro...@fenhi.uh.cu:
 Hi all..
 Sorry if this question sound elemental.
 How is the sintaxis for set the TODO and FIXME tags...?

There is no special syntax for those. Some people use them in
comments, but it's just a convention.

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


Re: Code for finding the 1000th prime

2009-11-17 Thread Chris Rebert
On Tue, Nov 17, 2009 at 9:27 AM, Diez B. Roggisch de...@nospam.web.de wrote:
 Stefan Behnel wrote:
 Robert P. J. Day, 15.11.2009 15:44:
 Now, all that's left to do is write a prime number generator (a random
 number generator will do, too, but writing a good one isn't easy), run it
 repeatedly in a loop, and check if the returned number is 7919. Once it
 compares equal, you can print the result and you're done.

 That reminds me of the only algorithm I really invented myself: debil sort.

There's prior art for this algorithm:
http://en.wikipedia.org/wiki/Bogosort

 It goes like this:

 L = list of comparable items

 while not sorted(L):
   p = generate_random_permutation(len(L))
   L = apply_permutation(L, p)

 print L


 Great algorithm. Actually works. And the saddest thing: somebody out there
 certainly has written something like that by accident... I've spotted
 sorting in O(n^3) (with non-deterministic exceptional termination
 conditions) already in the wild.

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


Re: python simply not scaleable enough for google?

2009-11-17 Thread Chris Rebert
On Tue, Nov 17, 2009 at 8:41 AM, Rustom Mody rustompm...@gmail.com wrote:
 Language L is (in)efficient. No! Only implementations are (in)efficient

 I am reminded of a personal anecdote.  It happened about 20 years ago
 but is still fresh and this thread reminds me of it.

 I was attending some workshop on theoretical computer science.
 I gave a talk on Haskell.

 I showed off all the good-stuff -- pattern matching, lazy lists,
 infinite data structures, etc etc.
 Somebody asked me: Isnt all this very inefficient?
 Now at that time I was a strong adherent of the Dijkstra-religion and
 this viewpoint efficiency has nothing to do with languages, only
 implementations traces to him. So I quoted that.

 Slowing the venerable P S Thiagarajan got up and asked me:
 Lets say that I have a language with a type 'Proposition'
 And I have an operation on proposition called sat [ sat(p) returns
 true if p is satisfiable]...

 I wont complete the tale other than to say that Ive never had the wind
 in my sails taken out so completely!

 So Vincent? I wonder what you would have said in my place?

I'm not Vincent, but: The sat() operation is by definition in
inefficient, regardless of language?

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


Re: TypeError: unsupported operand types for +: 'NoneType' and 'str'

2009-11-17 Thread Chris Rebert
On Tue, Nov 17, 2009 at 7:25 PM,  aurfal...@gmail.com wrote:
snip
 The error I get;

 File myscript.py, Line 18, in ?
 projectpath = ourHome+/etc/TEMPLATE
 TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

 Python 2.4.3

 I've read were when passing a string to exec may need to end with a '\n'

 I've tried a few diff variations on the below line 18 w/o luck.  Any one
 mind helping out a bratha from anatha ... planet that is?

 line 18;

 projectpath = ourHome+/etc/TEMPLATE

 line 17;
 ourHome = os.environ.get('some_env')

From the `os` docs:
os.environ
A mapping object representing the string environment.

From the `dict` docs (`dict` being the built-in and prototypical mapping class):
D.get(k[,d]) - D[k] if k in D, else d.  d defaults to None.

From this, I conclude that the environment variable `some_env` does
not exist for you, thus .get() returns None, thus causing an error
when you try and concatenate it with a string.

Solution: Either fix things so the environment variable does exist or
add code to handle the case of the environment variable not existing.

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


Re: WindowsError is not available on linux?

2009-11-17 Thread Chris Rebert
On Tue, Nov 17, 2009 at 7:37 PM, Peng Yu pengyu...@gmail.com wrote:
 On Tue, Nov 17, 2009 at 9:18 PM, alex23 wuwe...@gmail.com wrote:
 Peng Yu pengyu...@gmail.com wrote:
 But the document doesn't say shutil need to be imported in order to
 use WindowsError. Shall the document or the code be corrected?

 Neither, it's your understanding that needs correction.

 Benjamin wasn't trying to say that WindowsError is defined within
 shutil, he was showing that it _isn't_ defined within shutil on a non-
 Windows machine.

 As you're looking in shutil.py, you should have noticed this at the
 very top, just beneath the declaration of the Error exception:

    try:
        WindowsError
    except NameError:
        WindowsError = None

 This looks for the existence of the WindowsError exception - present
 only under Windows - and if it's not there it binds the name to None.
 You'll notice that the only place it's used in shutil.py is prefixed
 by the test WindowsError is not None...

 I think the mention of the exception being raised when a Windows-
 specific error occurs should make it pretty clear that this is a
 Windows-only exception.

 I don't know about others. The wording Windows-specific error occurs
 was ambiguous to me. It could refers to some errors resulted from
 copying (on a linux machine) some files from linux file systems to
 windows files systems (via samba, maybe). I recommend to revise the
 document a little bit to avoid confusion.

But your example isn't even Windows-specific because Samba server
exists; any error would network-related or specific to the SMB
protocol rather than Windows-related.

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


Re: Running a python script from interactive mode

2009-11-17 Thread Chris Rebert
On Tue, Nov 17, 2009 at 8:56 PM, ashwini yal ashwini...@gmail.com wrote:
 Hi,

 I am trying to run a python script from interactive mode ,but i am not able
 to know how to run it? Is it possible? if yes please let me how to run the
 script?

execfile(/path/to/the/script.py)

or if it's on your sys.path
and doesn't use the `if __name__ == __main__:` idiom
then just importing it works:

import script_name

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


Re: Language mavens: Is there a programming with if then else ENDIF syntax?

2009-11-18 Thread Chris Rebert
On Wed, Nov 18, 2009 at 1:15 AM, Steve Howell showel...@yahoo.com wrote:
 On the topic of switch statements and even-more-concise-then-we-have-
 already if/elif/else/end constructs, I have to say that Python does
 occasionally force you to write code like the code below.  Maybe
 force is too strong a word, but Python lends itself to if/elif
 blocks like below, which get the job done just fine, but which are not
 syntactically pretty, due to the (el){0,1}if kind == duplication.
 There are often cases where if/elif statements are just a smell that
 you do not know how to do dictionary lookups, but if you converted the
 below code to use dictionary lookups, you would complicate the code
 almost as much as you abstracted the code, if not more, unless I am
 just being very naive.

I'm gonna have to disagree and say using the dictionary dispatch
technique would clean it up a good bit.
Yes, it would entail creating several functions, but those functions
could then be documented (vs. the currently opaque code blocks); and
due to their separation and smaller length, they would be easier to
understand and test than the given code.
Additionally, the sheer length of the given code segment probably
constitutes a code smell in and of itself for the function containing
that code.

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


Re: break LABEL vs. exceptions + PROPOSAL

2009-11-18 Thread Chris Rebert
On Wed, Nov 18, 2009 at 4:05 AM, Lo'oris loo...@gmail.com wrote:
 I've found this email, back from 10 years ago:
 http://mail.python.org/pipermail/python-list/1999-September/009983.html

 I guess it went unnoticed, because that proposal looks really
 intresting.

 • break labels have been refused into python
 • we can do it anyway using exceptions
 • this is a proposal for something better, resembling the exception
 way and much more powerful and python-like than break labels

You're gonna have to wait 18-24 months:
http://www.python.org/dev/peps/pep-3003/

Also, the python-ideas list might be a better forum for discussing
this than the general-interest list:
http://mail.python.org/mailman/listinfo/python-ideas

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


Re: Minimally intrusive XML editing using Python

2009-11-18 Thread Chris Rebert
On Wed, Nov 18, 2009 at 4:55 AM, Thomas Lotze tho...@thomas-lotze.de wrote:
 I wonder what Python XML library is best for writing a program that makes
 small modifications to an XML file in a minimally intrusive way. By that I
 mean that information the program doesn't recognize is kept, as are
 comments and whitespace, the order of attributes and even whitespace
 around attributes. In short, I want to be able to change an XML file while
 producing minimal textual diffs.

 Most libraries don't allow controlling the order of and the whitespace
 around attributes, so what's generally left to do is store snippets of
 original text along with the model objects and re-use that for writing the
 edited XML if the model wasn't modified by the program. Does a library
 exist that helps with this? Does any XML library at all allow structured
 access to the text representation of a tag with its attributes?

Have you considered using an XML-specific diff tool such as:
* One off this list:
http://www.manageability.org/blog/stuff/open-source-xml-diff-in-java
* xmldiff (it's in Python even): http://www.logilab.org/859
* diffxml: http://diffxml.sourceforge.net/

[Note: I haven't actually used any of these.]

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


Re: DOM related question and problem

2009-11-18 Thread Chris Rebert
On Wed, Nov 18, 2009 at 10:04 AM, elca high...@gmail.com wrote:
 Hello,
 these day im making python script related with DOM.

 problem is these day many website structure is very complicate .

 what is best method to check DOM structure and path..

 i mean...following is some example.

 what is best method to check  can extract such like following info quickly?

 before i was spent much time to extract such info .

 and yes im also new to python and DOM.

    IE.Document.Frames(1).Document.forms('comment').value = 'hello'

 if i use DOM inspector, can i extract such info quickly ? if so would you
 show me some sample?

 here is some site . i want to extract some dom info.

 today i was spent all day long to extract what is dom info. but failed

 http://www.segye.com/Articles/News/Politics/Article.asp?aid=20091118001261ctg1=06ctg2=00subctg1=06subctg2=00cid=010101060

 at the end of this page,can find some comment input box.

 i want to know what kind of dom element should have to use, such like

    IE.Document.Frames(1).Document.forms('comment').value = 'hello'

 anyhelp much appreciate thanks

This sounds suspiciously like a spambot. Why do you want to submit
comments in an automated fashion exactly?

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


Re: DeprecationWarning on md5

2009-11-18 Thread Chris Rebert
On Wed, Nov 18, 2009 at 5:23 PM, Zeynel azeyn...@gmail.com wrote:
 Hello,

 I am a newbie both in Scrapy and Python. When I create a project with
 Scrapy I get these errors:

 C:\Python26\lib\site-packages\twisted\python\filepath.py:12:
 DeprecationWarning: the sha module is deprecated; use the hashlib
 module instead import sha
 C:\Python26\lib\site-packages\twisted\spread\pb.py:30:
 DeprecationWarning: the md5 module is deprecated; use hashlib instead
 import md5
 C:\Python26\lib\site-packages\twisted\mail\smtp.py:10:
 DeprecationWarning: the MimeWriter module is deprecated; use the email
 package instead

 I found several references to this bug but I could not understand
 how to fix it. Can anyone help?

This is a bug in the version of Twisted you're using. What Python is
saying is that Twisted is using some modules from the Python stdlib
that are deprecated and will be removed in some future version of
Python, thus Twisted will /eventually/ need to be changed to use the
newer replacement library.
However, this is only a warning, not an error; the code will run just
fine until you update to the eventual Python version that removed said
deprecated libraries (by which time a new Twisted version will
probably be available with the necessary fixes made).

So, basically you can safely ignore the warnings, unless you want to
custom-patch your Twisted installation, which I wouldn't particularly
recommend.
It's also entirely possible your Twisted is outdated and a new version
fixed to avoid using the deprecated modules is already available.

If you want to suppress the output of the warnings, see the docs for
the `warnings` module:
http://docs.python.org/library/warnings.html

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


Re: combinatorics via __future__ generators

2009-11-18 Thread Chris Rebert
On Wed, Nov 18, 2009 at 4:58 PM, Phlip phlip2...@gmail.com wrote:
 Python:

 I have a quaint combinatorics problem. Before I solve it, or find a
 solution among generators, I thought y'all might like to show off
 any solutions.

 Given an array like this...

  [0, 4, 3]

 Produce an array like this:

  [
    [0, 0, 0],
    [0, 1, 0],
    [0, 2, 0],
    [0, 3, 0],
    [0, 1, 1],
    [0, 2, 1],
    [0, 3, 1],
    [0, 1, 2],
    [0, 2, 2],
    [0, 3, 2],
 ]

 The first array is the counts of options in 4 slots, and the second is
 all combinations of indexes of each option, such that every option
 associates once with every other option. The leading 0 simply
 represents a slot with no options; the algorithm must preserve those.

 This should be child's play for the generator package, right?

from itertools import imap, product

def special_range(n):
return (xrange(n) if n else [0])

def something(arr):
return product(*imap(special_range, arr))

print list(something([0,4,3]))

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


Re: What is the naming convention for accessor of a 'private' variable?

2009-11-18 Thread Chris Rebert
On Wed, Nov 18, 2009 at 6:27 PM, Peng Yu pengyu...@gmail.com wrote:
 http://www.python.org/dev/peps/pep-0008/

 The above webpage states the following naming convention. Such a
 variable can be an internal variable in a class. I'm wondering what is
 the naming convention for the method that access such variable.

    - _single_leading_underscore: weak internal use indicator.  E.g. from M
      import * does not import objects whose name starts with an underscore.

If there's a method to access the variable, then it's not all that
private, is it?
Accessor methods are not Pythonic. Just make the attribute public by
not prefixing it with an underscore.

See also Python is Not Java:
http://dirtsimple.org/2004/12/python-is-not-java.html

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


Re: Invitation to connect on LinkedIn

2009-11-18 Thread Chris Rebert
On Wed, Nov 18, 2009 at 6:16 PM, Jim Qiu bluefishe...@gmail.com wrote:

 LinkedIn

 Jim Qiu requested to add you as a connection on LinkedIn:

 Jaime,

 I'd like to add you to my professional network on LinkedIn.

 - Jim


 Accept View invitation from Jim Qiu


 WHY MIGHT CONNECTING WITH JIM QIU BE A GOOD IDEA?

 Jim Qiu's connections could be useful to you
 After accepting Jim Qiu's invitation, check Jim Qiu's connections to see who 
 else you may know and who you might want an introduction to. Building these 
 connections can create opportunities in the future.



 © 2009, LinkedIn Corporation

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

Could one of the list admins please reset the password and change the
email on this guy's LinkedIn account?
How the heck someone sets their account email to a mailinglist, I'll
never figure out.

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


Re: convert a string to a regex?

2009-11-18 Thread Chris Rebert
On Wed, Nov 18, 2009 at 6:51 PM, Peng Yu pengyu...@gmail.com wrote:
 There are many special characters listed on
 http://docs.python.org/library/re.html

 I'm wondering if there is a convenient function that can readily
 convert a string with the special characters to its corresponding
 regex. For example,

 some.thing = some\.thing

If you'd taken 45 seconds to scan the documentation:

http://docs.python.org/library/re.html#re.escape

re.escape(string)
Return string with all non-alphanumerics backslashed; this is
useful if you want to match an arbitrary literal string that may have
regular expression metacharacters in it.

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


Re: What is the naming convention for accessor of a 'private' variable?

2009-11-18 Thread Chris Rebert
On Wed, Nov 18, 2009 at 7:04 PM, Peng Yu pengyu...@gmail.com wrote:
 On Wed, Nov 18, 2009 at 8:47 PM, Chris Rebert c...@rebertia.com wrote:
 On Wed, Nov 18, 2009 at 6:27 PM, Peng Yu pengyu...@gmail.com wrote:
 http://www.python.org/dev/peps/pep-0008/

 The above webpage states the following naming convention. Such a
 variable can be an internal variable in a class. I'm wondering what is
 the naming convention for the method that access such variable.

    - _single_leading_underscore: weak internal use indicator.  E.g. from 
 M
      import * does not import objects whose name starts with an underscore.

 If there's a method to access the variable, then it's not all that
 private, is it?
 Accessor methods are not Pythonic. Just make the attribute public by
 not prefixing it with an underscore.

 See also Python is Not Java:
 http://dirtsimple.org/2004/12/python-is-not-java.html

 I don't quite understand the following paragraph from the above
 webpage. Would you please give me an example to help me understand it?

 Here's what you do. You write a function that contains a function.
 The inner function is a template for the functions that you're writing
 over and over again, but with variables in it for all the things that
 vary from one case of the function to the next. The outer function
 takes parameters that have the same names as those variables, and
 returns the inner function. Then, every place where you'd otherwise be
 writing yet another function, simply call the outer function, and
 assign the return value to the name you want the duplicated function
 to appear. Now, if you need to change how the pattern works, you only
 have to change it in one place: the template.

#untested off-the-cuff example:

from time import time

def add_timing(func): # takes a function as an argument
Wraps functions so they output their execution time when called
def wrapper(*args, **kwargs): #defines a new function
start = time()
# thanks to closures, we can access func here
result = func(*args, **kwargs) # have the new function call
the given function
end = time()
duration = end-start
print Call to, func.__name__, took, duration, seconds
return result
return wrapper # return the new function so that it can replace
the function it calls

def long_calculation(x, y, z):
# some code

long_calculation = add_timing(long_calculation)

print long_calculation(1, 7, 42)

#Example output:
#Call to long_calculation took 135.5 seconds
#99

Now imaging applying add_timing to multiple functions and note the
amount of code you'd save and how the unrelated concerns of timing and
mathematical calculation (or whatever the functions you apply
add_timing() to do) would then be cleanly separated.
The same technique can be applied to logging and other repetitive code
to factor it out.
It's sort of like aspect-oriented programming, but not as kludgey.

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


Re: crontab problem

2009-11-21 Thread Chris Rebert
On Sat, Nov 21, 2009 at 5:47 AM, Victor Subervi victorsube...@gmail.com wrote:
 Hi;
 I have the following in crontab -eu root:
 @daily /usr/local/bin/mysql-backup-daily.sh
 @weekly /usr/local/bin/mysql-backup-weekly.sh
 @monthly /usr/local/bin/mysql-backup-monthly.sh

 [r...@13gems globalsolutionsgroup.vi]# ls /usr/local/bin/mysql-*
 /usr/local/bin/mysql-daily.sh  /usr/local/bin/mysql-monthly.sh
 /usr/local/bin/mysql-weekly.sh

 These scripts worked on another server. The daily writes to:
 /usr/backup/database/mysql-backups/mysql-backup-dailys/
 However, a day later, nothing is there. Please advise.

And this is germane to Python (and not instead say, *nix) how exactly?

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


Re: Sorting: too different times. Why?

2009-11-22 Thread Chris Rebert
On Sun, Nov 22, 2009 at 2:56 AM, n00m n...@narod.ru wrote:
 I was expecting the 1st method would be *slower* than the 2nd one :-)
 Or at least equal... Just random (intuitive) expectations

The second method repeatedly looks up left_item.__class__.__cmp__
(i.e. Vector.__cmp__) when doing the necessary comparisons between the
list items; while these lookups are optimized and are fast, they are
not free and cannot be skipped because Python doesn't know the list
contains only Vectors.
The first method uses the single provided comparison function and thus
does no such lookups; hence, it's faster.

That's my guess anyway.

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


Re: Why Python allows comparison of a callable and a number?

2009-11-22 Thread Chris Rebert
On Sun, Nov 22, 2009 at 4:03 AM, 一首诗 newpt...@gmail.com wrote:
 I used python to write an assignment last week, here is a code snippet

 #

 def departTime():
    '''
    Calculate the time to depart a packet.
    '''
    if(random.random  0.8):
        t = random.expovariate(1.0 / 2.5)
    else:
        t = random.expovariate(1.0 / 10.5)
    return t

 #

 Can you see the problem?  I compare random.random with 0.8,  which
 should be random.random().

 Of course this because of my careless, but I don't get it.  In my
 opinion, this kind of comparison should invoke a least a warning in
 any programming language.

 So why does python just ignore it?

It's an historical anomaly that's been rectified in Python 3, where
such non-equality comparisons between unrelated types *do* now raise
an error.

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


Re: attributes, properties, and accessors -- philosophy

2009-11-23 Thread Chris Rebert
On Mon, Nov 23, 2009 at 10:52 AM, Ethan Furman et...@stoneleaf.us wrote:
 The problem I have with properties is my typing.  I'll end up assigning to
 an attribute, but get the spelling slightly wrong (capitalized, or missing
 an underscore -- non-obvious things when bug-hunting), so now I have an
 extra attribute which of course has zero effect on what I'm trying to do and
 I start getting wierd results like viewing deleted records when I *know* I
 set useDeleted = False... 30 minutes later I notice it was /supposed/ to be
 use_deleted.  *sigh*

 So -- to keep myself out of trouble -- I have started coding such things as,
 for example:

 result = table.use_deleted()       # returns True or False
 table.use_deleted(False)           # skip deleted records

 instead of

 result = table.use_deleted
 table.use_deleted = False

 My question:  is this [ severely | mildly | not at all ] un-pythonic?

Yes, it's unpythonic. Use something like pychecker, pylint, or
pyflakes, which will catch the sorts of typo errors you talk about.

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


Re: pointless musings on performance

2009-11-24 Thread Chris Rebert
On Tue, Nov 24, 2009 at 4:31 AM, Rob Williscroft r...@freenet.co.uk wrote:
 mk wrote in news:mailman.915.1259064240.2873.python-l...@python.org in
 comp.lang.python:


 def pythonic():

 def unpythonic():


 Decidedly counterintuitive: are there special optimizations for if
 nonevar: type of statements in cpython implementation?


 from dis import dis

 dis( unpythonic )

 18          31 LOAD_FAST                0 (nonevar)
             34 LOAD_CONST               0 (None)
             37 COMPARE_OP               9 (is not)
             40 JUMP_IF_FALSE            4 (to 47)

 dis( pythonic )

 11          31 LOAD_FAST                0 (nonevar)
             34 JUMP_IF_FALSE            4 (to 41)

In other words, CPython doesn't happen to optimize `if nonevar is not
None` as much as it theoretically could (which would essentially
require a JUMP_IF_NONE opcode). Since CPython isn't known for doing
fancy optimizations, this isn't surprising.

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


Re: attributes, properties, and accessors -- philosophy

2009-11-24 Thread Chris Rebert
On Tue, Nov 24, 2009 at 9:39 AM, Ethan Furman et...@stoneleaf.us wrote:
 Bruno Desthuilliers wrote:
 Ethan Furman a écrit :
 The problem I have with properties is my typing.  I'll end up assigning
 to an attribute, but get the spelling slightly wrong (capitalized, or
 missing an underscore -- non-obvious things when bug-hunting), so now I have
 an extra attribute which of course has zero effect on what I'm trying to do
 and I start getting wierd results like viewing deleted records when I *know*
 I set useDeleted = False... 30 minutes later I notice it was /supposed/ to
 be use_deleted.  *sigh*

 So -- to keep myself out of trouble -- I have started coding such things
 as, for example:

 result = table.use_deleted()       # returns True or False
 table.use_deleted(False)           # skip deleted records

 instead of

 result = table.use_deleted
 table.use_deleted = False

 My question:  is this [ severely | mildly | not at all ] un-pythonic?


 Definitly and totally unpythonic. The first solution to your problem is to
 stick to standard naming conventions. If this is not enough, Chris pointed
 you to really useful tools. Also, you can override __setattr__ to catch such
 errors - at least during the coding/debug phase.

 Good tools to know about, and a consistent naming pattern also makes life
 easier (which I have since done ;).

 Let's head towards murkier waters (at least murkier to me -- hopefully they
 can be easily clarified):  some of the attributes are read-only, such as
 record count; others are not directly exposed, but still settable, such as
 table version; and still others require a small amount of processing... at
 which point do I switch from simple attribute access to method access?

Thanks to the magic of properties, the end-user-programmer need not
know which you're using:

http://docs.python.org/library/functions.html#property

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


Re: get line number and filename in a source file

2009-11-24 Thread Chris Rebert
On Tue, Nov 24, 2009 at 9:47 PM, Peng Yu pengyu...@gmail.com wrote:
 __LINE__ __FILE__ in C++ can give the current line number and
 filename. Is there a similar thing in python that can give me the
 current line number and filename?

import inspect
filename, linenum, funcname = inspect.getframeinfo(inspect.currentframe())[:3]

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


Re: Can self crush itself?

2009-11-25 Thread Chris Rebert
On Wed, Nov 25, 2009 at 1:46 AM, n00m n...@narod.ru wrote:
 Then how can we destroy the 3rd instance,
 right after its creation and from inside
 class Moo code?

Why would you want to do that in the first place? It's strange to say the least.
If you want to prevent an instance being created in the first place,
you can override __new__().

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


Re: Feature request: String-inferred names

2009-11-25 Thread Chris Rebert
On Wed, Nov 25, 2009 at 6:35 PM, The Music Guy
fearsomedragon...@gmail.com wrote:
 Hello all,

 I just posted to my blog about a feature that I'd like to see added to
 Python. Before I go through the trouble of learning how to write a PEP or
 how to extend the Python interpreter, I want to know what people in the
 community have to say about it.

 http://alphaios.blogspot.com/2009/11/python-string-inferred-names-working.html

 As far as I know, a feature like this does not appear in any existing PEPs.
 (If it does I would appreciate it if someone could tell me what PEP it is.)

 Please give and comments you may have, but I request that you be
 constructive if you must criticize...thank you!

Ugly, Perlish, and as you even admit, entirely unnecessary.
And you'd need to wait at least a year anyway:
http://www.python.org/dev/peps/pep-3003/

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Chris Rebert
On Sun, Nov 29, 2009 at 4:39 PM, Esmail ebo...@hotmail.com wrote:
 Ok, this is somewhat unexpected:

 Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
 [GCC 4.3.3] on linux2
 Type help, copyright, credits or license for more information.


 -3**2
 -9

 x = -3

 x**2
 9


 I would have expected the same result in both cases.

 Initially I would have expected -3**2 to yield 9, but I can accept
 that ** binds tighter than the unary -, but shouldn't the results
 be consistent regardless if I use a literal or a variable?

_No_, because using the variable evaluates -3 as a unit separately
by itself, before the exponentiation ever occurs; it's the same as the
difference between (-3)**2 and -3**2.
Python is not a concatenative programming language[*]; you can't
directly textually replace a variable with its value and expect to get
the same result from an expression. For instance, in this case, you
need to add the parentheses.

Cheers,
Chris
--
http://blog.rebertia.com

[*] http://en.wikipedia.org/wiki/Concatenative_language
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noobie python shell question

2009-11-29 Thread Chris Rebert
On Sun, Nov 29, 2009 at 7:53 PM, Tim Chase
python.l...@tim.thechases.com wrote:
snip
 (as an aside, is there a way to get a local/global variable from a string
 like one can fetch a variable from a class/object with getattr()?  Something
 like getattr(magic_namespace_here, hello) used in the above context?  I
 know it can be done with eval(), but that's generally considered unsafe
 unless you vet your input thoroughly)

locals()[hello]  and  globals()[hello], respectively

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


Re: Unpacking Tuples

2009-11-30 Thread Chris Rebert
On Mon, Nov 30, 2009 at 12:17 AM, Joel Davis callmeclaud...@gmail.com wrote:
 I hate to post such a simple Q and A here, but I seriously can't find
 it anywhere. Python (unsure of starting with which version) enables
 the remainder of the tuple to be placed in a catch-all, for example:


 myTuple = (1,2,3,4)
 varOne, varTwo, *remaindingTuple = myTuple.

 where the values left unpacked get thrown into a tuple referenced to
 by remaindingTuple I included the asterix because it seems like I
 remember that being the operator that specifying the tuple's dumping
 ground. Which brings me to my two questions:
 1) what's the syntax for this operation

Exactly as you showed above (well, minus the period obviously).

2) what version does it start with?

Python 3.0

It might be backported into 2.7 when it gets released:
http://bugs.python.org/issue2340

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


Re: python and vc numbers

2009-11-30 Thread Chris Rebert
On Mon, Nov 30, 2009 at 2:02 AM, Daniel Dalton d.dal...@iinet.net.au wrote:

 On Mon, Nov 30, 2009 at 07:20:59PM +1100, Daniel Dalton wrote:
 That did the trick, thanks, after I append
 [-2]

 Further testing under screen says otherwise -- it seems to give me the
 tty number, not the virtual console number. Is there any way to figure
 out what virtual console I'm am in so a certain command ran under screen
 process A isn't confused with a command ran under screen process B?

From what I can find, virtual console == tty.
Quoting http://en.wikipedia.org/wiki/Virtual_console_%28PC%29
The virtual consoles are represented by device special files
/dev/tty1, /dev/tty2 etc.

Also, in my quickie newbie experimentation with `screen`, each screen
window seems to get a unique tty#. Admittedly I am running OS X
here, so if your notion of virtual console differs from Wikipedia's
and is Linux-specific or something...

Perhaps if you could explain your problem in greater detail?

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-30 Thread Chris Rebert
 On Mon, Nov 30, 2009 at 3:46 AM, Gregory Ewing
 greg.ew...@canterbury.ac.nz wrote:
 Esmail wrote:

 Wow .. never heard of Concatenative_languages languages before or the
 distinction you make. Your distinction explains the behavior, but I
 find it somewhat counter-intuitive.

 You shouldn't find it any more surprising than the fact that

  a = 2 + 3
  print a * 5

 gives a different result from

  print 2 + 3 * 5

On Mon, Nov 30, 2009 at 3:41 AM, inhahe inh...@gmail.com wrote:
 one point of confusion could be the use of ** instead of superscript.
 it might make things a little bit more counterintuitive-looking than
 with superscripts, since the issue with

Well, since source code is almost universally just plain ASCII and not
in some file format with typesetting, superscripts aren't going to
happen any time soon.
(Also, avoid top-posting in the future.)

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


Re: Function parameters list

2009-12-01 Thread Chris Rebert
On Tue, Dec 1, 2009 at 12:15 AM, Nadav Chernin nada...@qualisystems.com wrote:
 Hello, all

 I need to know dynamically parameters of any function (prototype).

 Is there some way to get it?

The `inspect` module:

http://docs.python.org/library/inspect.html#inspect.getargspec
http://docs.python.org/library/inspect.html#inspect.formatargspec

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


Re: python bijection

2009-12-01 Thread Chris Rebert
On Tue, Dec 1, 2009 at 5:17 PM, Aahz a...@pythoncraft.com wrote:
 In article 
 85100df7-a8b0-47e9-a854-ba8a8a2f3...@r31g2000vbi.googlegroups.com,
 Joshua Bronson  jabron...@gmail.com wrote:

I noticed the phonebook example in your ActiveState recipe and thought
you might consider changing it to something like husbands to wives,
since the names-to-phone-numbers relation is many-to-many.

 What makes you think husbands to wives is one-to-one?  ;-)  (Even
 assuming monogamy, you have husbands-to-husbands and wives-to-wives.)

Reminds me of this quite funny blog post:
Gay marriage: the database engineering perspective
http://qntm.org/?gay

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


Re: commands module for windows

2009-12-01 Thread Chris Rebert
On Tue, Dec 1, 2009 at 10:05 PM, M Kumar tomanis...@gmail.com wrote:
 Is there any python module for windows which is equivalent to commands
 module in linux?

`subprocess` should work: http://docs.python.org/library/subprocess.html

The `commands` docs even say:
The subprocess module provides more powerful facilities for spawning
new processes and retrieving their results.
Using the subprocess module is preferable to using the commands module.

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


Re: commands module for windows

2009-12-01 Thread Chris Rebert
 On Wed, Dec 2, 2009 at 11:42 AM, Chris Rebert c...@rebertia.com wrote:
 On Tue, Dec 1, 2009 at 10:05 PM, M Kumar tomanis...@gmail.com wrote:
  Is there any python module for windows which is equivalent to commands
  module in linux?

 `subprocess` should work: http://docs.python.org/library/subprocess.html

 The `commands` docs even say:
 The subprocess module provides more powerful facilities for spawning
 new processes and retrieving their results.
 Using the subprocess module is preferable to using the commands module.

On Tue, Dec 1, 2009 at 10:34 PM, M Kumar tomanis...@gmail.com wrote:
 can I use this module to store output to a python variable?
 I am looking for something similar to
 commands.getoutput(cmd)

Yes, of course it can. If it's more powerful, then it can do
everything the other module can.
It'd be silly for the `commands` docs to point people to `subprocess`
if this wasn't the case.
It will take more than a single line of code though. Read the module's docs.

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


Re: Don't Understand This Error

2009-12-02 Thread Chris Rebert
On Wed, Dec 2, 2009 at 2:33 AM, Victor Subervi victorsube...@gmail.com wrote:
 I get the following error:

  /var/www/html/angrynates.com/cart/chooseOptions.py
     8 from login import login
     9 import string
    10 import options
    11 from particulars import optionsTables, addStore
    12
 options undefined

 SyntaxError: invalid syntax (options.py, line 140)
   args = ('invalid syntax',
 ('/var/www/html/angrynates.com/cart/options.py', 140, 85,  colorsTables,
 colorsNames = colors('products', 'specificTables', specificTables):\n))
   filename = '/var/www/html/angrynates.com/cart/options.py'
   lineno = 140
   msg = 'invalid syntax'
   offset = 85
   print_file_and_line = None
   text =  colorsTables, colorsNames = colors('products',
 'specificTables', specificTables):\n

 I don't understand the 'text = ... part of the last line.

It's the text of the specific line of code that caused the error, I think.

 Here's the line from the code:

     colorsTables, colorsNames = colors('products', 'specificTables',
 specificTables):

The syntax error is that you have an illegal colon at the end of that
line. Remove that colon.

 No text. I'm just calling a function and getting the results. Here's the
 pared-down function:

 def colors(callingTable, which='', specificTables=[]):

The error lies in the caller of colors().

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


Re: prolog with python

2009-12-02 Thread Chris Rebert
On Wed, Dec 2, 2009 at 6:47 PM, William Heath wghe...@gmail.com wrote:
 Hi All,

 I have the following prolog program that I would really like to be able to
 run in python in some elegant way:

From googling:

http://pyke.sourceforge.net/
http://code.activestate.com/recipes/303057/

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


Re: Declaring a class level nested class?

2009-12-02 Thread Chris Rebert
On Wed, Dec 2, 2009 at 8:55 PM, cmckenzie mckenzi...@gmail.com wrote:
 Hi.

 I'm new to Python, but I've managed to make some nice progress up to
 this point. After some code refactoring, I ran into a class design
 problem and I was wondering what the experts thought. It goes
 something like this:

 class module:
   nestedClass

   def __init__():
      self.nestedClass = nested()
      print self.nestedClass.nestedVar

   class nested():
      nestedVar = 1
      def __init__(self):
         print Initialized...

 I can't figure out what the correct way to construct the nested
 class so it can belong to module.

 I want a class level construct of nested to belong to module, but
 I keep getting nestedClass isn't defined.

Here's the scoping reason why it fails (remember that the nested class
is a class variable of the containing class):

BEGIN PENDING FAQ SUBMISSION

Why do I get errors when accessing class variables (a.k.a. static variables)?
-
If you try something like the following::

class Foo(object):
class_variable = 42

def method(self, x):
return x + class_variable


Foo().method(7)

You'll get an error about Python being unable to find the class variable::

Traceback (most recent call last):
 ...
NameError: global name 'class_variable' is not defined

This is because class-level scope is not consulted when looking up
plain names in methods.  When looking up a name, the following scopes
are consulted, in order: Local variables, Variables in nested
functions, Global variables, and finally, Built-ins.

To refer to class variables, you must be more explicit. There are several
ways to go about it:

* Refer to the class by name::

def method1(self, x):
return x + Foo.class_variable

* Refer to the class of the object dynamically. If you class is
subclassed, this will allow the subclasses to override the value of
the class variable. ::

def method2(self, x):
return x + self.__class__.class_variable

* Exploit the fact that attribute lookups on an object fall back to
its class. Be warned that if you have both instance and class variables
with the same name, the instance variable will shadow
the class variable. ::

def method3(self, x):
return x + self.class_variable

* If your method is not truly an instance method
(i.e. does not utilize ``self``), make it a class method ::

@classmethod
def method4(cls, x):
return x + cls.class_variable

END FAQ EXCERPT

However, there's pretty much no reason to nest classes anyway in
Python (it's not Java!). Just make them both top-level in the file. If
one class is only used internally in the module, just use the normal
private naming convention of starting its name with an underscore.

Also note that class names should generally use StudlyCaps, and that
naming a class module is rather confusing.

Cheers,
Chris
--
If the Python.org webmasters are listening, add the FAQ entry already!
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with function prototype

2009-12-03 Thread Chris Rebert
On Thu, Dec 3, 2009 at 3:02 AM, Nadav Chernin nada...@qualisystems.com wrote:
 Hi, all

 In past I asked about module – inspect, that can’t to get me prototype of
 C-implemented functions ( usually all built-in functions ).

 But, still I see that all Python Editors ( IDLE for example ) can to show
 prototype of built-in functions – by tooltip. When you print for example:
 sum(, you see what kind of parameters you must to enter.

 So, how IDLE know it?

It doesn't really; it only shows the function's docstring, which /just
so happens/ to document the parameters in the particular case of the
built-in functions:

$ python
Python 2.6.2
Type help, copyright, credits or license for more information.
 print sum.__doc__
sum(sequence[, start]) - value

Returns the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).  When the sequence is
empty, returns start.
 type(sum.__doc__)
type 'str'

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


Re: Directly converting Python to C using the C API

2009-12-03 Thread Chris Rebert
On Thu, Dec 3, 2009 at 6:09 PM, Emmanuel Bengio beng...@gmail.com wrote:
 I'm fairly new to the python world, and I often heard critics about it's
 speed, and also about it's non-compilability.
 Then I thought, there is a complete C API that manages Python itself.
 Would it be feasible to transform pure Python code into pure Python C API
 code? It would spare the parsing time, which seems to be the an important
 factor in Python's speed.

 Given the following example:
 x=0
 for i in xrange(10):
     x+=x*i
 On my machine, this takes 79ms to run.
 while this:
 PyObject* x = PyInt_FromLong(0);
 int i;
 for (i=0;i10;i++)
 {
     x=PyNumber_Add(x,PyNumber_Multiply(x,PyInt_FromLong(i)));
 }
 takes about 16 ms to run.
 Any thoughts?

You're going to have to check that xrange() hasn't been rebound for starters.

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


Re: read from standard input

2009-12-04 Thread Chris Rebert
On Fri, Dec 4, 2009 at 9:37 PM, Siva B sivait...@gmail.com wrote:
 Hi all,

 I wrote a program to read some data through standard input and write in a
 file.
 the following code works fine in linux.
 but its giving ArgumentError in windows.

There's no such error in Python; you're thinking of Ruby.
Unless you give the /actual/ error (with message) and full traceback,
there's not much we can do to help you besides just guess.

snip
 file=open('data.txt','w')

Don't use `file` as a variable name, you're shadowing the built-in type.

 and what is the command in windows for EOF (like Cntrl D in linux)

http://tinyurl.com/yggsby3
The *very first result* has the answer in its 6th sentence.

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


Re: read from standard input

2009-12-04 Thread Chris Rebert
 On Sat, Dec 5, 2009 at 11:54 AM, Chris Rebert c...@rebertia.com wrote:

 On Fri, Dec 4, 2009 at 9:37 PM, Siva B sivait...@gmail.com wrote:
  Hi all,
 
  I wrote a program to read some data through standard input and write in
  a
  file.
  the following code works fine in linux.
  but its giving ArgumentError in windows.

 There's no such error in Python; you're thinking of Ruby.
 Unless you give the /actual/ error (with message) and full traceback,
 there's not much we can do to help you besides just guess.

 snip
  file=open('data.txt','w')

 Don't use `file` as a variable name, you're shadowing the built-in type.

  and what is the command in windows for EOF (like Cntrl D in linux)

 http://tinyurl.com/yggsby3
 The *very first result* has the answer in its 6th sentence.

On Fri, Dec 4, 2009 at 11:13 PM, Siva B sivait...@gmail.com wrote:
 Hi Chris,
 Thanks for you reply.
 The error log is here for my above program in windows:

 Traceback (most recent call last):
   File C:\Documents and Settings\user\Desktop\t1.py, line 3, in module
 orig_source = sys.stdin.read()
 AttributeError: read

Okay, that Shouldn't Be Happening (tm). Add the following before line
3 and post the output:

print type(sys.stdin), sys.stdin

And while we're at it, what version of Python are your running?

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


Re: How to create a docstring for a module?

2009-12-06 Thread Chris Rebert
On Sun, Dec 6, 2009 at 12:34 PM, Dr. Phillip M. Feldman
pfeld...@verizon.net wrote:
 OK.  I was able to reproduce the problem.  My difficulty was that the command
 that I issued initially was from xyz import * rather than just import
 xyz.  If I say import xyz, then the docstring is defined; if I say from
 xyz import *, it isn't.  I'm not sure whether this is a bug or expected
 behavior.

Expected behavior. If you `from foo import bar`, the name `foo` won't
be bound, so needless to say you won't be able to access its docstring
foo.__doc__.

$ ipython
Python 2.6.2 (r262:71600, Nov  5 2009, 15:03:16)
Type copyright, credits or license for more information.

IPython 0.10 -- An enhanced Interactive Python.
? - Introduction and overview of IPython's features.
%quickref - Quick reference.
help  - Python's own help system.
object?   - Details about 'object'. ?object also works, ?? prints more.

In [1]: ?pickle
Object `pickle` not found.

In [2]: from pickle import *

In [3]: ?pickle
Object `pickle` not found.

In [4]: pickle.__doc__
---
NameError Traceback (most recent call last)

/Users/chris/ipython console in module()

NameError: name 'pickle' is not defined

In [5]: import pickle

In [6]: ?pickle

shows the documentation

In [7]: pickle.__doc__
Out[7]: 'Create portable serialized representations of Python
objects.\n\nSee module cPickle for a (much) faster
implementation.\nSee module copy_reg for a mechanism for registering
custom picklers.\nSee module pickletools source for extensive
comments.\n\nClasses:\n\nPickler\nUnpickler\n\nFunctions:\n\n
  dump(object, file)\ndumps(object) - string\nload(file) -
object\nloads(string) - object\n\nMisc variables:\n\n
__version__\nformat_version\ncompatible_formats\n\n'


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


Re: dict.fromkeys strange behavior

2009-12-07 Thread Chris Rebert
On Mon, Dec 7, 2009 at 12:42 AM, Tsviki Hirsh tsviki.hi...@gmail.com wrote:
 Dear list,
 I'm trying to create a dictionary from set of keys and values using
 dict.fromkeys
 When I type:
dict.fromkeys('a',50)
 the output is:
 {'a': 50}
 This is fine, but when I try to set the same value to a different name key:
dict.fromkeys('at',50)
 the output now is:
 {'a': 50, 't': 50}
 This is obviously not what I wanted.
 What are the alternatives?

 dict.fromkeys(['at'],50)
{'at': 50}

Remember that strings are collections too (of individual characters).

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


Re: hola

2009-12-07 Thread Chris Rebert
2009/12/6 franki fuentes cueto ffrankis...@gmail.com:
 hola soy un pequeño programador y quiesiera pedirles ayuda para programar en
 python, no se si me podrian mandar ejemplos para poder empezar, y como
 terminarlo para que se ejecute, me entiendes , aver sime ayudan gracias

Esta lista de discusión es en Inglés.

Hay una lista de discusión en Español aqui:
http://listas.aditel.org/listinfo/python-es

Salud,
Chris
--
Sé solamente un poquito de Español.
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: switch

2009-12-08 Thread Chris Rebert
On Tue, Dec 8, 2009 at 5:53 PM, hong zhang henryzhan...@yahoo.com wrote:
 Python does not have switch statement. Any other option does similar work?

Yes, a dictionary with functions as values:
http://simonwillison.net/2004/May/7/switch/

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


Re: Generating diagrams from PostgreSQL with Python (Re: postgresql_autodoc in Python?)

2009-12-10 Thread Chris Rebert
On Thu, Dec 10, 2009 at 3:48 AM, Diez B. Roggisch de...@nospam.web.de wrote:
 Wolfgang Keller wrote:

 Hello,

 I will re-precise my question:

 Has anyone ever implemented a script in Python that generates
 documentation (especially diagrams, in a format such as e.g. Dia, Inkscape
 SVG or Tikz) for a PostgreSQL database either from an SQL script or by
 connecting to the database?

 I've written a schemadiff-tool for postgres based on SQLAlchemy reflection,
 which is a branch of SQLAlchemy and which should become part of the
 upcoming SA 0.6.

 http://svn.sqlalchemy.org/sqlalchemy/branches/reflection

 It allows you to extract information about the schema of the DB. This could
 be the foundation of your tool.


 Postgresql_autodoc is unfortunately written in Perl. ;-

 TIA,

 And, btw., please respect my .sig,

 Which is supposed to mean what? Never heard the term courtesy copy.

It appears to be an incorrect expansion of Cc, which is actually
Carbon copy. Apparently he means all replies should be directly to the
list and not Cc his individual email address.
Which seems strange, because usually mailinglists are smart enough not
to send the author duplicate copies if they're named in the To or Cc
fields.

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


Re: read text file byte by byte

2009-12-13 Thread Chris Rebert
On Sun, Dec 13, 2009 at 12:20 AM, Michel Claveau - MVP
enleverlesx_xx...@xmclavxeaux.com.invalid wrote:
 Hi!

 If it's a binary file...

 OK, but... what is a binary file?

http://en.wikipedia.org/wiki/Binary_file

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


Re: unable to read the __main__ namespace

2009-12-13 Thread Chris Rebert
On Sun, Dec 13, 2009 at 3:20 AM, vsoler vicente.so...@gmail.com wrote:
 I'm learning Python, and I am very fond of it.

 Using Python 2.6

 I am able to list all the names in a class namespace:

 class abc: pass
 abc.a1=7
 abc.a2='Text'

 print abc.__dict__.keys()

That is more simply written as:

print dir(abc)

 a) However, I do not know how to read the __main__ namespace

 print __main__.__dict__.keys()    # Just does not work

__main__ is not used or set and has no special meaning to the Python
interpreter. It's true that __name__ == __main__ in the body of the
main module, but you can't actually access it by that name.

 b) How do i read an imported module namespace?

import module
print dir(module)

 c) How could I possibly list the names and contents of the namespace
 of my python session?

print dir()

I'd advise reading the docs on it:
http://docs.python.org/library/functions.html#dir

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


Re: insert unique data in a list

2009-12-13 Thread Chris Rebert
On Sun, Dec 13, 2009 at 5:19 PM, knifenomad knifeno...@gmail.com wrote:
 On 12월14일, 오전2시57분, mattia ger...@gmail.com wrote:
 Il Sun, 13 Dec 2009 16:37:20 +, mattia ha scritto:
  How can I insert non-duplicate data in a list? I mean, is there a
  particular option in the creation of a list that permit me not to use
  something like:
  def append_unique(l, val):
      if val not in l:
          l.append(val)

 Ok, so you all suggest to use a set. Now the second question, more
 interesting. Why can't I insert a list into a set? I mean, I have a
 function that returns a list. I call this function several times and
 maybe the list returned is the same as another one already returned. I
 usually put all this lists into another list. How can I assure that my
 list contains only unique lists? Using set does'n work (i.e. the python
 interpreter tells me: TypeError: unhashable type: 'list')...

 this makes the set type hashable.

 class Set(set):
    __hash__ = lambda self: id(self)

Or you could just use frozenset and get the correct semantics:
http://docs.python.org/library/stdtypes.html#frozenset

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


Re: dictionary with tuple keys

2009-12-14 Thread Chris Rebert
On Mon, Dec 14, 2009 at 9:49 PM, Brandon Devine your.mas...@gmail.com wrote:
 Hi all,

 I am probably not thinking straight anymore about this problem.  I
 have a dictionary with tuple keys in the format (a, b, A, B) and float
 values.  I want to collect all the keys with identical (a, b...),
 disregarding whatever (... A, B) might be.  Specifically, I want to
 sum the float values once I've collected these keys.  I am staring at
 my screen, pondering ugly things, and I just know I must be missing a
 Pythonic solution.  Any suggestions?

from collections import defaultdict

new_dict = defaultdict(int)
for tupkey in your_dict:
new_key = tupkey[:2]
new_dict[new_key] += your_dict[tupkey]

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


Re: csv reader

2009-12-15 Thread Chris Rebert
On Tue, Dec 15, 2009 at 1:24 PM, Emmanuel manou...@gmail.com wrote:
 I have a problem with csv.reader from the library csv. I'm not able to
 import accentuated caracters. For example, I'm trying to import a
 simple file containing a single word equação using the following
 code:

 import csv
 arquivoCSV='test'
 a=csv.reader(open(arquivoCSV),delimiter=',')
 tab=[]
 for row in a:
    tab.append(row)
 print tab

 As a result, I get:

 [['equa\xe7\xe3o']]

 How can I solve this problem?

From http://docs.python.org/library/csv.html :

Note:
This version of the csv module doesn’t support Unicode input. Also,
there are currently some issues regarding ASCII NUL characters.
Accordingly, all input should be UTF-8 or printable ASCII to be safe;
see the examples in section Examples. These restrictions will be
removed in the future.


Thus, you'll have to decode the results into Unicode manually; this
will require knowing what encoding your file is using. Files in some
encodings may not parse correctly due to the aforementioned NUL
problem.

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


Re: Odd json encoding erro

2009-12-15 Thread Chris Rebert
On Tue, Dec 15, 2009 at 2:03 PM, Wells thewellsoli...@gmail.com wrote:
 I get this exception when decoding a certain JSON string:

 'ascii' codec can't encode character u'\u2019' in position 8: ordinal
 not in range(128)

 The JSON data in question:

 http://mlb.com/lookup/json/named.player_info.bam?sport_code=%27mlb%27player_id=%27489002%27

 It's in the 'high_school' key. Is there some string function I can run
 on the information before I decode it to avoid this?

From what I can guess (you didn't include any code), you're printing
the result of loading the JSON (which probably loaded correctly) to
the terminal without specifying the exact encoding to use. In such
cases, Python defaults to ASCII. However, your data obviously includes
non-ASCII characters, thus resulting in the error you're encountering.
Instead of `print the_high_school`, try `print
the_high_school.encode('utf8')`.

Note that the `json` library returns Unicode strings of the type
`unicode` and not byte strings of type `str` (unless you're using
Python 3.0, in which case `unicode` got renamed to `str` and `str` got
renamed to `bytes`). When outputting Unicode, it needs to be encoded
to bytes. The built-in type() function* can help determine when you
have Unicode data.

Cheers,
Chris
--
http://blog.rebertia.com

*Yes, it's not /really truly/ a function, but the distinction is not
relevant here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Odd json encoding erro

2009-12-15 Thread Chris Rebert
On Tue, Dec 15, 2009 at 3:04 PM, Wells thewellsoli...@gmail.com wrote:
 Sorry- more detail- the actual problem is an exception thrown when
 running str() on the value, like so:

 a = u'St. Paul\u2019s School For Boys (MN) HS'
 print str(a)
 Traceback (most recent call last):
  File stdin, line 1, in module
 UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in
 position 8: ordinal not in range(128)

 Is there some way to run str() against a unicode object?

To repeat what I said earlier, you use the .encode() method instead:

print a.encode('utf8')

Might I recommend reading:
http://www.joelonsoftware.com/articles/Unicode.html

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


Re: strptime not strict enough

2009-12-15 Thread Chris Rebert
On Tue, Dec 15, 2009 at 9:47 PM, Tim Roberts t...@probo.com wrote:
 Tobias Weber t...@gmx.net wrote:

despite the directives for leading zero stime.strptime('09121',
'%y%m%d') returns the first of December. Shouldn't it raise ValueError?

 Python merely calls the strptime function in your C run-time library.  If
 it sucks, so will time.strptime.

Er, no, wrong: 
http://svn.python.org/view/python/trunk/Lib/_strptime.py?view=markup

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


Re: Storing a Value in a Cookie

2009-12-16 Thread Chris Rebert
On Wed, Dec 16, 2009 at 1:13 AM, Victor Subervi victorsube...@gmail.com wrote:
 Hi;
 From what I've studied and gotten working about cookies, it seems one can
 store only a certain few pieces of information--expiration, path, comment,
 domain, max-age, version and last visit--but how is it useful if one can't
 also store, say, the name of a temporary MySQL table where pertinent
 customer data, such as shopping cart data, is stored? I guess I could put
 that into the comment field, but I suspect there's a better way of doing it.
 Please advise.

Besides the metadata you mentioned, a cookie can also store one
key-value pair, which is sent as the first part of the Cookie HTTP
header when setting the cookie (Cookie: name=value); this is
typically used to store a session ID.
It is inadvisable to store much data other than a session ID in a
cookie because as a rule, in order to avoid security risks, clients
should not be trusted. In the example you give of storing the name of
an SQL table, someone could guess the name of another user's SQL table
and alter their cookie to masquerade as that user, thus compromising
the other customer's shopping cart, and depending on the contents of
the SQL table, potentially their credit card.
Most web frameworks, like Django, will handle low-level details like
setting and getting cookies for you and provide a higher-level API for
dealing with sessions and/or users.

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


Re: Can't Iterate

2009-12-16 Thread Chris Rebert
On Wed, Dec 16, 2009 at 11:26 PM, Victor Subervi
victorsube...@gmail.com wrote:
 Hi;
 I have this line of code:

 for store in ourStores():

 which is called from the statement:

 from particulars import ourStores

 The latter file has the following:

 def ourStores():
   return ['prescriptions', 'products']

 Yet, the above iteration only iterates the last of these items ('products').
 Why?

To put it mildly: Unable to reproduce the problem.
Post a more complete code sample. For instance, include whatever
debugging code is leading you to believe that only products is being
yielded by the iteration.

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


Re: py itertools?

2009-12-19 Thread Chris Rebert
On Sat, Dec 19, 2009 at 2:54 AM, mattia ger...@gmail.com wrote:
 Hi all, I need to create the permutation of two strings but without
 repeat the values, e.g. 'ab' for me is equal to 'ba'. Here is my
 solution, but maybe the python library provides something better:

 def mcd(a, b):
 ...     if b == 0:
 ...         return a
 ...     else:
 ...         return mcd(b, a % b)
 ...
 def mcm(a, b):
 ...     return int((a * b) / mcd(a, b))
 ...
 s1 = 'abc'
 s2 = 'wt'
 m = mcm(len(s1), len(s2))
 set(zip(s1*m, s2*m))
 {('a', 'w'), ('a', 't'), ('b', 'w'), ('c', 't'), ('b', 't'), ('c', 'w')}

 Any help?

Surprised you didn't think of the seemingly obvious approach:

def permute_chars(one, two):
for left in set(one):
for right in set(two):
yield (left, right)

 list(permute_chars('abc', 'wt'))
[('a', 'w'), ('a', 't'), ('b', 'w'), ('b', 't'), ('c', 'w'), ('c', 't')]

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


Re: Class variables static by default?

2009-12-19 Thread Chris Rebert
On Sat, Dec 19, 2009 at 8:16 PM, Steven D'Aprano
st...@remove-this-cybersource.com.au wrote:
 On Sun, 20 Dec 2009 11:44:11 +1100, Lie Ryan wrote:

 In python, 'class variable' is a variable that belongs to a class; not
 to the instance and is shared by all instance that belong to the class.

 Surely, since string variables are strings, and float variables are
 floats, and bool variables are bools, and module variables are modules, a
 class variable will be a class and an instance variable will be an
 instance?

As they say, the exception proves the rule. :)

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


Re: Something Like os.environ['HTTP_REFERER']

2009-12-20 Thread Chris Rebert
On Sun, Dec 20, 2009 at 2:06 AM, Victor Subervi victorsube...@gmail.com wrote:
 Hi;
 I'm looking for something like os.environ['HTTP_REFERER'] but for python
 scripts. That is, if I have a script that is imported by another script, how
 can I have the script that is being imported determine which script imported
 it?

Allow me to ask the meta-question of: Why do you want to do that?
There is quite possibly a better means to accomplish whatever end you have.

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


Re: Mails encoding

2009-12-20 Thread Chris Rebert
On Sun, Dec 20, 2009 at 2:46 AM, Lord Eldritch
lord_eldri...@yahoo.co.uk wrote:
snip
 - When I have:

 ttext='áá'

 I get a warning sendinme to this page

 http://www.python.org/peps/pep-0263.html

 Should I understand that PEP has been already implemented and follow it?

Yes.

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


Re: Import Problem

2009-12-20 Thread Chris Rebert
On Sun, Dec 20, 2009 at 3:34 AM, Victor Subervi victorsube...@gmail.com wrote:
snip
 But I get this error:

 /var/www/html/angrynates.com/cart/createTables2.py
   263 /html
   264 '''
   265
   266 createTables2()
   267
 createTables2 = function createTables2
  /var/www/html/angrynates.com/cart/createTables2.py in createTables2()
   105 these.append(basic)
   106   i = 0
   107   specialtyStore = addStore()
   108   addStore = []

Rename this list so its name isn't the same as the addStore() function
which you call. For more info, see:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/46b4c8af3196caaa?pli=1

   109   addStore.append(specialtyStore)
 specialtyStore undefined, global addStore = function addStore

 UnboundLocalError: local variable 'addStore' referenced before assignment
   args = (local variable 'addStore' referenced before assignment,)

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


Re: py itertools?

2009-12-20 Thread Chris Rebert
 On Dec 19, 12:48 pm, Chris Rebert c...@rebertia.com wrote:
 On Sat, Dec 19, 2009 at 2:54 AM, mattia ger...@gmail.com wrote:
  Hi all, I need to create the permutation of two strings but without
  repeat the values, e.g. 'ab' for me is equal to 'ba'. Here is my
  solution, but maybe the python library provides something better:

  def mcd(a, b):
  ...     if b == 0:
  ...         return a
  ...     else:
  ...         return mcd(b, a % b)
  ...
  def mcm(a, b):
  ...     return int((a * b) / mcd(a, b))
  ...
  s1 = 'abc'
  s2 = 'wt'
  m = mcm(len(s1), len(s2))
  set(zip(s1*m, s2*m))
  {('a', 'w'), ('a', 't'), ('b', 'w'), ('c', 't'), ('b', 't'), ('c', 'w')}

  Any help?

 Surprised you didn't think of the seemingly obvious approach:

 def permute_chars(one, two):
     for left in set(one):
         for right in set(two):
             yield (left, right)

  list(permute_chars('abc', 'wt'))

 [('a', 'w'), ('a', 't'), ('b', 'w'), ('b', 't'), ('c', 'w'), ('c', 't')]

On Sun, Dec 20, 2009 at 3:21 AM, Parker xeno...@gmail.com wrote:
 a = 'qwerty'
 b = '^%$#'
 c = [(x,y) for x in a for y in b]
 c
 [('q', '^'), ('q', '%'), ('q', ''), ('q', '$'), ('q', '#'), ('w',
 '^'), ('w', '%'), ('w', ''), ('w', '$'), ('w', '#'), ('e', '^'),
 ('e', '%'), ('e', ''), ('e', '$'), ('e', '#'), ('r', '^'), ('r',
 '%'), ('r', ''), ('r', '$'), ('r', '#'), ('t', '^'), ('t', '%'),
 ('t', ''), ('t', '$'), ('t', '#'), ('y', '^'), ('y', '%'), ('y',
 ''), ('y', '$'), ('y', '#')]


 This one is better and simple.

But fails if either of the input strings has repeated characters.
(Although writing it as a comprehension is indeed much briefer.)

Whether this matters, who knows, since the OP's spec for the function
was rather vague...

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


Re: Create attribute from string

2009-12-30 Thread Chris Rebert
On Wed, Dec 30, 2009 at 9:22 PM, AON LAZIO aonla...@gmail.com wrote:
 Hi,
     I would like to know how we could create attribute from string

 say I want to assign value 0.05 to an object attribute

 I like to input SIGNIFICANT and 0.05 and get
 object.SIGFICANT equals to 0.05

setattr(obj, SIGNIFICANT, 0.05)

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


Re: Exception as the primary error handling mechanism?

2009-12-31 Thread Chris Rebert
On Thu, Dec 31, 2009 at 8:47 PM, Peng Yu pengyu...@gmail.com wrote:
 I observe that python library primarily use exception for error
 handling rather than use error code.

 In the article API Design Matters by Michi Henning

 Communications of the ACM
 Vol. 52 No. 5, Pages 46-56
 10.1145/1506409.1506424
 http://cacm.acm.org/magazines/2009/5/24646-api-design-matters/fulltext

 It says Another popular design flaw—namely, throwing exceptions for
 expected outcomes—also causes inefficiencies because catching and
 handling exceptions is almost always slower than testing a return
 value.

 My observation is contradicted to the above statement by Henning. If
 my observation is wrong, please just ignore my question below.

 Otherwise, could some python expert explain to me why exception is
 widely used for error handling in python? Is it because the efficiency
 is not the primary goal of python?

Correct; programmer efficiency is a more important goal for Python instead.
Python is ~60-100x slower than C;[1] if someone is worried by the
inefficiency caused by exceptions, then they're using completely the
wrong language.

Cheers,
Chris
--
http://blog.rebertia.com

[1] 
http://shootout.alioth.debian.org/u64/which-programming-languages-are-fastest.php?gcc=onpython=oncalc=chart
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Significant whitespace

2010-01-01 Thread Chris Rebert
On Fri, Jan 1, 2010 at 2:02 PM, Dan Stromberg drsali...@gmail.com wrote:
 I put together a page about significant whitespace (and the lack thereof).

 You're invited to check it out:

 http://stromberg.dnsalias.org/~dstromberg/significant-whitespace.html

For those of us who weren't around during the heyday of FORTRAN, can
anyone describe this apparently much-reviled significant whitespace
feature that continues to make some programmers unjustly fearful about
Python's use of indentation?

Thanks in advance.

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


Re: Significant whitespace

2010-01-01 Thread Chris Rebert
On Fri, Jan 1, 2010 at 9:56 PM, Donn donn.in...@gmail.com wrote:
 On Saturday 02 January 2010 00:02:36 Dan Stromberg wrote:
 I put together a page about significant whitespace (and the lack thereof).
 The only thing about Python's style that worries me is that it can't be
 compressed like javascript can*, and perhaps that will prevent it becoming a
 browser-side language one day. How I'd love to code PyQuery instead of JQuery!

 * Or am I wrong?

Not to my knowledge, but CPython's bytecode format could be used to
similar effect.

However, the larger and much more daunting obstacle to client-side
Python would be that it's not sandboxed or secured like JavaScript is,
although there are some people working on it.

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


Re: TypeError: can only concatenate list (not tuple) to list

2010-01-04 Thread Chris Rebert
On Sun, Jan 3, 2010 at 11:51 PM, Gabriel Genellina
gagsl-...@yahoo.com.ar wrote:
 This
 py [1,2,3] + (4,5)
 Traceback (most recent call last):
  File stdin, line 1, in module
 TypeError: can only concatenate list (not tuple) to list

Given that tuples are sometimes used as a poor man's object (i.e.
collection of data fields), whereas lists are not typically used that
way, I'd say it's probably a good thing an explicit type conversion is
required here.

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


Re: Can't Add Variable

2010-01-04 Thread Chris Rebert
On Mon, Jan 4, 2010 at 9:28 AM, Victor Subervi victorsube...@gmail.com wrote:
 Hi;
 I have this code snippet:

     sql '''create table if not exists %sCustomerData (

You're missing an equal sign there to start with (i.e. sql = ''').

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


Re: How to validate the __init__ parameters

2010-01-04 Thread Chris Rebert
On Mon, Jan 4, 2010 at 10:17 AM, Albert van der Horst
alb...@spenarnc.xs4all.nl wrote:
snip
 This triggers a question: I can see the traceback, but it
 would be much more valuable, if I could see the arguments
 passed to the functions. Is there a tool?

print(locals()) #this actually gives the bindings for the entire local namespace
#but is less work than writing something more precise by hand.

It is amazing how handy the humble print() function/statement is when debugging.

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


Re: Newbie help- Can multiple instances with multiple names automatically created.

2010-01-04 Thread Chris Rebert
On Mon, Jan 4, 2010 at 1:32 PM, Shawn Milochik sh...@milochik.com wrote:
 You could put them in a dictionary with the key being the name, instead of a 
 list.

To illustrate that for the OP:

name2drink = {}
for booze in liquors:
for juice in juices:
name = juice + +booze # or however you're naming them
drink = Bottle(booze, juice)
name2drink[name] = drink

#example use
favorite = name2drink[apple wine]
favorite.rating = 9/10

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


Re: Exception as the primary error handling mechanism?

2010-01-05 Thread Chris Rebert
much snippage
On Tue, Jan 5, 2010 at 1:07 AM, r0g aioe@technicalbloke.com wrote:
 Lie Ryan wrote:
 I have been looking at Haskell recently and the way the pure functional
 language handled exceptions and I/O gives me a new distinct insight
 that exceptions can be thought of as a special return value that is
 implicitly wrapped and unwrapped up the call stack until it is
 explicitly handled.

 Yes there's some very interesting paradigms coming out of functional
 programming but, unless you're a maths major, functional languages are a
 long way off being productivity tools! Elegant: yes, provable: maybe,
 practical for everyday coding: not by a long shot!

Methinks the authors of Real World Haskell (excellent read btw) have a
bone to pick with you.

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


Re: Exception as the primary error handling mechanism?

2010-01-05 Thread Chris Rebert
On Tue, Jan 5, 2010 at 3:51 PM, Phlip phlip2...@gmail.com wrote:
 Peng Yu wrote:
 Otherwise, could some python expert explain to me why exception is
 widely used for error handling in python? Is it because the efficiency
 is not the primary goal of python?

 It's not about efficiency, it's about making assumptions for the
 programmer about what kind of rigor they need.

 Why can't int('nonnumeric') return None?

Errors should never pass silently.
Unless explicitly silenced.
-- The Zen of Python (http://www.python.org/dev/peps/pep-0020/)

Better to throw an exception and ensure the case is specifically dealt
with one way or another than to silently return an error flag result
which may only delay the error until later in the program, making it
harder to debug. Is it that much of a burden to write and use the
small function that does what you want?

def int_or_None(string):
try:
return int(string)
except ValueError:
return None

Heck, you can even write it inline and dispense with the function if you want:

try: foo = int(bar)
except ValueError: foo = None

Quibbling over a mere one more line of code (or writing one short
function) seems a bit petty.

 (A related question - why can't I just go 'if record = method():  use
 (record)'. Why extra lines just to trap and assign the variable before
 using it?)

I believe that's disallowed so as to prevent the subtle bugs seen in C
code which result from when someone makes a typo and omits the second
= in their `if foo == bar():` test.

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


Re: Exception as the primary error handling mechanism?

2010-01-05 Thread Chris Rebert
On Tue, Jan 5, 2010 at 5:45 PM, Phlip phlip2...@gmail.com wrote:
 On Jan 5, 5:01 pm, Chris Rebert c...@rebertia.com wrote:
  Why can't int('nonnumeric') return None?

 Errors should never pass silently.

 You are saying I, as the programmer, cannot decide what is an error
 and what is a pass-thru. The decision is made for me. (Yes yes I can
 write int_or_None(), etc...)

No, you can certainly decide yourself. You merely need be explicit
about it; you're leaving out the other tandem half of the couplet:
*Unless* explicitly silenced. Throwing exceptions is only the
default because it tends to lead to more reliable code in that you're
forced to deal with the error condition by either catching an
exception or preventing one from being thrown (by, say, using a
different method in the API that just returns a default value
instead).

As an aside, I would guess the built-in types don't have default value
parameters for conversions partly because it'd be a bit less elegant
to implement; since None is a commonly used default value, they'd have
to use a different sentinel as said parameter's default value to
indicate that the caller wanted an exception raised, and having a
hierarchy of nil values in the core language detracts from the
language's elegance.

At any rate, if you like dict.get(), I don't see why, say,
my_int('nonnumeric', None) should be such a problem.

 Here's a super easy example:

  { 42: 'forty two' }.get(41, None)

 Because I can supply a default, I can decide what is an error and what
 is .

Exactly, that's explicitly silencing the error; no one ever said an
`except` clause was the only silencing mechanism. You're making your
intention clear by using .get() and passing in a desired default. I
agree this is a fine thing.

 Now the equivalent in a language that does not enjoy this false Zen:

  { 42: 'forty two' }[41]  # returns None
  { 42: 'forty two' }.fetch(41, None)  # ibid
  { 42: 'forty two' }.fetch(41)  # raises an exception

 The quicky validation is available if I _request_ it.

Seems like rather fast-and-loose programming if you don't care about
validation enough of the time to merit it being default. If your
programming is indeed so fast-and-loose, I refer you to the recent
comment about PHP (and other less exception-happy languages).

Anyway, I do totally agree that you should, if feasible, be provided
an easy way to designate a common error-handling strategy (for
example, in this case, by using a default value via .fetch()).

However, go too loose on error handling and exceptions and one ends up
with something like JavaScript with its infamous `undefined` value
which can make debugging a nightmare (whoever came up with the idea of
JS's `undefined` should be slapped upside the head).

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


Re: buffer interface problem

2010-01-07 Thread Chris Rebert
On Thu, Jan 7, 2010 at 12:19 AM, Andrew Gillanders
andrew.gilland...@uqconnect.edu.au wrote:
 I have run into a problem running a Python script that is part of the
 TerraGear suite for building scenery for FlightGear. I am using Mac OS X
 10.4, running Python (version 3.0.1) in a Unix terminal.

 The purpose of the script is to walk a directory tree, unzipping files, and
 passing the contents to an executable C program. The problem occurs here:

    gzin = GzipFile(fname, 'rb')
    data = gzin.readline()
    min_x,min_y = map(atoi,data.split()[:2])

 The input file, when uncompressed, is an ASCII file with a line with two
 numbers, then a line of four numbers, then many long lines of numbers. I can
 see what the last is trying to do: split the string into two words, convert
 them to integers, and assign them to min_x and min_y.

 At the third line, I get the message expected an object with the buffer
 interface. Which object is it referring to?

The elements of the list produced by `data.split()[:2]`, which are
either Unicode strings or bytestrings, neither of which are buffers.

 Have some functions been
 changed to pass buffer objects instead of strings? How can I fix the source
 code to make it run?

The error is being raised by the atoi() function (in the future,
please post the full Traceback, not just the final error message).
What module/library does your atoi() function come from (look for an
`import` statement mentioning it)?
The only functions by that name in the Python standard library both
operate on strings, not buffers, and thus can't be the same one your
code is using.

In any case, replacing `atoi` with `int` in your code will likely
solve the problem. The built-in int() function* can convert strings to
integers.

Cheers,
Chris
--
http://blog.rebertia.com

*Not really a function, but close enough for newbie explanatory purposes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: buffer interface problem

2010-01-07 Thread Chris Rebert
On Thu, Jan 7, 2010 at 4:47 AM, Andrew Gillanders
andrew.gilland...@uqconnect.edu.au wrote:
 On 07/01/2010, at 7:13 PM, Chris Rebert wrote:
 On Thu, Jan 7, 2010 at 12:19 AM, Andrew Gillanders
 andrew.gilland...@uqconnect.edu.au wrote:

 I have run into a problem running a Python script that is part of the
 TerraGear suite for building scenery for FlightGear. I am using Mac OS X
 10.4, running Python (version 3.0.1) in a Unix terminal.

 The purpose of the script is to walk a directory tree, unzipping files,
 and
 passing the contents to an executable C program. The problem occurs here:

   gzin = GzipFile(fname, 'rb')
   data = gzin.readline()
   min_x,min_y = map(atoi,data.split()[:2])

 The input file, when uncompressed, is an ASCII file with a line with two
 numbers, then a line of four numbers, then many long lines of numbers. I
 can
 see what the last is trying to do: split the string into two words,
 convert
 them to integers, and assign them to min_x and min_y.

 At the third line, I get the message expected an object with the buffer
 interface. Which object is it referring to?

 The elements of the list produced by `data.split()[:2]`, which are
 either Unicode strings or bytestrings, neither of which are buffers.

 Have some functions been
 changed to pass buffer objects instead of strings? How can I fix the
 source
 code to make it run?

 The error is being raised by the atoi() function (in the future,
 please post the full Traceback, not just the final error message).
 What module/library does your atoi() function come from (look for an
 `import` statement mentioning it)?
 The only functions by that name in the Python standard library both
 operate on strings, not buffers, and thus can't be the same one your
 code is using.

 In any case, replacing `atoi` with `int` in your code will likely
 solve the problem. The built-in int() function* can convert strings to
 integers.

 Thanks Chris. The atoi function was coming from the locale library (from
 locale import atoi). I changed it to int and now it works.

Hm, that's odd since it was one of the 2 functions in the std lib
which the docs say operates on strings...

 The next hurdle is this:
gzin = GzipFile(fname, 'rb')

data = gzin.readline()
 #min_x,min_y = map(atoi,data.split()[:2])
min_x,min_y = map(int,data.split()[:2])

data = gzin.readline()
 #span_x,step_x,span_y,step_y = map(atoi,data.split()[:4])
span_x,step_x,span_y,step_y = map(int,data.split()[:4])

data = gzin.read().split('\n')

 The last line is a problem, giving me this message: Type str doesn't support
 the buffer API (I am guessing a conflict between split and read?)

Ah, looking at the 3.0 docs on buffers, I'd surmise gzin.read()
returns bytes (http://docs.python.org/3.1/library/functions.html#bytes)
rather than a string.
You'll want to decode the bytes into characters first, and then you
can operate on the resulting string normally.
Try:

data = gzin.read().decode('ascii').split('\n')

 Sorry, I am new to Python, so how do I get a Traceback?

You should get one by default. Are you running the script in some
environment other than the command line?

Here's what a traceback looks like:

Traceback (most recent call last):
  File foo, line 161, in module
main()
  File foo.py, line 157, in main
bot.run()
  File foo.py, line 68, in bar
self.baz(Enter number: )
  File foo.py, line 112, in baz
choice = int(raw_input(prompt))-1
ValueError: invalid literal for int() with base 10: 'y'

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


Re: Recommended new way for config files

2010-01-07 Thread Chris Rebert
On Thu, Jan 7, 2010 at 10:19 AM, Peter vm...@mycircuit.org wrote:
snip
 The .ini file is the simpliest solution, at least from the user point of
 view, no need to learn any python syntax.

 I am speaking from the point of view of a python programmer, and I find the
 .ini restrictions not necessarily simple, for example when dealing with
 structured data (I suppose it is trivial to specify a dictionnary or a list
 for the purpose of my request) For example, configuration files for the
 logging module get unwieldy when you specify several loggers , handlers,
 formatters etc, because you have to break down structured data ( objects )
 to name,value pairs.
snip
 So what is the worshipped approach, when you need more than name=value
 pairs ?

JSON is one option: http://docs.python.org/library/json.html

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


Re: Standardized interpreter speed evaluation tool

2010-01-08 Thread Chris Rebert
On Fri, Jan 8, 2010 at 2:25 AM, alexru tara...@gmail.com wrote:
 Is there any standardized interpreter speed evaluation tool? Say I
 made few changes in interpreter code and want to know if those changes
 made python any better, which test should I use?

Although apparently undocumented, test.pystone is some sort of
interpreter benchmark.

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


Re: integer and string compare, is that correct?

2010-01-10 Thread Chris Rebert
On Sun, Jan 10, 2010 at 4:26 AM, Hellmut Weber m...@hellmutweber.de wrote:
 Hi,
 being a causal python user (who likes the language quite a lot)
 it took me a while to realize the following:


 l...@sylvester py_count $ python
 Python 2.6.3 (r263:75183, Oct 26 2009, 12:34:23)
 [GCC 4.4.1] on linux2
 Type help, copyright, credits or license for more information.
 max = '5'
 n = 5
 n = max
 False
 n + max
 Traceback (most recent call last):
  File stdin, line 1, in module
 TypeError: unsupported operand type(s) for +: 'int' and 'str'



 Section 5.9 Comparison describes this.

 Can someone give me examples of use cases

The behavior of disparate types being comparable is deprecated and has
been removed in Python 3.0+; don't rely upon it. (The ordering used is
arbitrary but consistent)
IIRC, the feature existed in prior versions to make lists containing
mixed types sortable; this was found to be not all that useful and to
hide what are quite arguably errors.

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


Re: integer and string compare, is that correct?

2010-01-10 Thread Chris Rebert
On Sun, Jan 10, 2010 at 4:46 AM, Chris Rebert c...@rebertia.com wrote:
snip
 The behavior of disparate types being comparable is deprecated and has
 been removed in Python 3.0+; don't rely upon it.

Clarification: Equality testing between disparate types still works
unaltered however.
By comparable, I meant , , =, = comparisons.

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


Re: how to duplicate array entries

2010-01-10 Thread Chris Rebert
On Sun, Jan 10, 2010 at 10:21 PM, Sebastian sebastian.lan...@gmx.de wrote:
 Hi there,

 I have an array  x=[1,2,3]

 Is there an operator which I can use to get the result
 [1,1,1,2,2,2,3,3,3] ?

 I tried x*3, which resulted in [1,2,3,1,2,3,1,2,3]
 I also tried [[b,b,b] for b in x] which led to [[1,2,3],[1,2,3],
 [1,2,3]], but this isn't what I want either.

from itertools import chain, repeat
n = 3
stretched = list(chain(*[repeat(item, n) for item in x]))

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


Re: how to duplicate array entries

2010-01-11 Thread Chris Rebert
On Mon, Jan 11, 2010 at 1:03 AM, Alf P. Steinbach al...@start.no wrote:
 * Steven D'Aprano:

 On Mon, 11 Jan 2010 08:56:36 +0100, Alf P. Steinbach wrote:

 * Paul Rudin:

 Sebastian sebastian.lan...@gmx.de writes:

 I have an array  x=[1,2,3]

 In python such an object is called a list.

 (In cpython it's implemented as an automatically resizable array.)

 I don't think the OP's terminology needs correction.

 A Python list is an array functionality-wise.

 If one isn't observant of that fact then one ends up with O(n^2) time
 for the simplest things.

 Well that's certainly not true. Some operations may be O(N**2), but others
 are not: list.append() is amortized O(N) and for individual appends, may be
 can be as fast as O(1).

 The second sentence may or may not be true. I don't know of any fundamental
 'list' operations that have quadratic time. Is there?

 The first sentence is just baffling  --  what on Earth is the that that
 you think is not true?

 OK, I can guess (correct me if I'm guessing wrong, please): you think I'm
 talking about elementary operations. I'm not. I'm talking about algorithmic
 complexity for loops doing e.g. insertions.


 Using the term array accentuates and clarifies this most important
 aspect.

 But Python lists are designed to behave as lists.

 No, I'm sorry, they're not.

 A Python 'list' has de facto constant time indexing, or random access.

 A linked list  --  what the informal list means in programming

Eh, it's a bit context-dependent. The abstract data type definition is
a superset that includes both linked lists and dynamic arrays. FWIW,
Java likewise uses list in its ADT sense.

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


Re: how to duplicate array entries

2010-01-11 Thread Chris Rebert
On Mon, Jan 11, 2010 at 2:20 AM, Alf P. Steinbach al...@start.no wrote:
 * Chris Rebert:
 On Mon, Jan 11, 2010 at 1:03 AM, Alf P. Steinbach al...@start.no wrote:
 * Steven D'Aprano:
 On Mon, 11 Jan 2010 08:56:36 +0100, Alf P. Steinbach wrote:
 * Paul Rudin:
 Sebastian sebastian.lan...@gmx.de writes:
snip
 Using the term array accentuates and clarifies this most important
 aspect.

 But Python lists are designed to behave as lists.

 No, I'm sorry, they're not.

 A Python 'list' has de facto constant time indexing, or random access.

 A linked list  --  what the informal list means in programming

 Eh, it's a bit context-dependent. The abstract data type definition is
 a superset that includes both linked lists and dynamic arrays.

 Assuming you're talking about some abstract type definition that's in some
 PEP somewhere

No, I mean the computer science definition/term:
http://en.wikipedia.org/wiki/List_(computer_science)

 FWIW, Java likewise uses list in its ADT sense.

 I'm sorry, I'm unfamiliar with that Java terminology (but then, reportedly,
 many Java programmers think that Java has pass by reference, so nothing
 coming from that direction will surprise me very much!). The Java language
 specification has a section about arrays, none about lists AFAICS. Do you
 have a reference?

http://java.sun.com/j2se/1.4.2/docs/api/java/util/List.html

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


Re: os.system function

2010-01-11 Thread Chris Rebert
On Mon, Jan 11, 2010 at 12:43 PM, Zabin zabin.faris...@gmail.com wrote:
 Hey everyone!

 I am a new python programmer. I am trying to get the general file
 functionality with options of save and save as working. These save
 functions save a folder with multiple files. Upon using the os.system
 copy function- if my destination directory has files with similar
 names- i am asked whether i want to replace the files on the command
 prompt.

 Is there some way of getting this question into a dialog box?

 Also is there someway of avoiding or programmatically setting the
 response to the command prompt?

You can probably avoid using os.system() entirely (always a good
thing) by instead using the functions in the `shutil` library:
http://docs.python.org/library/shutil.html

And for future reference, the `subprocess` module is the preferred way
to invoke external programs, rather than os.system():
http://docs.python.org/library/subprocess.html

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


Re: What is built-in method sub

2010-01-11 Thread Chris Rebert
On Mon, Jan 11, 2010 at 12:34 PM, Steven D'Aprano
st...@remove-this-cybersource.com.au wrote:
snip
 If you can avoid regexes in favour of ordinary string methods, do so. In
 general, something like:

 source.replace(target, new)

 will potentially be much faster than:

 regex = re.compile(target)
 regex.sub(new, source)
 # equivalent to re.sub(target, new, source)

 (assuming of course that target is just a plain string with no regex
 specialness). If you're just cracking a peanut, you probably don't need
 the 30 lb sledgehammer of regular expressions.

Of course, but is the regex library really not smart enough to
special-case and optimize vanilla string substitutions?

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


Re: os.system function

2010-01-11 Thread Chris Rebert
On Mon, Jan 11, 2010 at 2:00 PM, Zabin zabin.faris...@gmail.com wrote:
snip
 and just wondering- whats the drawback of using os.system() command

Forgetting to properly escape your input. Simple example:

filename = foo bar.txt
os.system(rm +filename) # uh-oh, we deleted 'foo' and 'bar.txt' instead

The `subprocess` module makes escaping unnecessary.

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


Re: Python File Search

2010-01-11 Thread Chris Rebert
2010/1/11 Eknath Venkataramani eknath.i...@gmail.com:
 correct.txt snippet:
 1 2 1
 1 3 3
 1 5 21
 1 7 19

 union_output_TEMP.txt snippet:
 1 2 1_NN
 1 3 3_VBZ
 1 3 5_VBZ
 1 3 2_VBZ
 1 5 21_VB
 1 7 19_NN
 1 9 14_VB

 I need to get the output in categorized.txt as:
 NN={1 7 19, 1 2 1}
 VBZ={1 3 3}
 VB={1 5 21}

 in python.
 Kindly help

We don't do other's homework
(http://in.linkedin.com/pub/eknath-venkataramani/17/1a9/b55), but are
willing to give hints.
I would give a more clear explanation of what this is supposed to do
if you want useful advice.
For example, why does NN contain all matching entries when the other 2
only include the first matching entries?

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


Re: A question about Python versions

2010-01-12 Thread Chris Rebert
On Tue, Jan 12, 2010 at 10:09 PM, Gib Bogle
g.bo...@auckland.no.spam.ac.nz wrote:
 I am learning Python, and using PyQt to develop a GUI that will be used to
 run a Fortran program on Windows, Linux and Mac OS X (I think Python is
 great, btw). Without thinking about it I downloaded and started working with
 a fairly recent Python version, 2.5.4.  I've now become aware of the
 existence of Python 3.1, which apparently is a major revision of the
 language.  Does it make sense to stick with Python 2.x at this point, or
 should I be starting off with 3.1?

This is an FAQ, so you can search the archives for many other
responses. If your program needs to use any third-party libraries
besides PyQt, you should probably use 2.x as most libraries have yet
to be ported to 3.x yet (luckily, PyQt apparently has been ported
already). If your program will be pretty self-sufficient, Python 3 is
definitely an option and will be nicer to use thanks to the
improvements to the language, but most of the changes (aside from
strings becoming Unicode) aren't dramatic; it is clearly still the
same language (unlike Perl 5 - Perl 6).

 If it is recommended to stick with
 version 2, should I use the latest (2.6.4 or 2.7), and if so why?  Thanks.

The latest stable one, 2.6.4 (2.7 is a preview release); there's no
reason not to, and newer versions have more features, bugfixes, etc.
Though you should double-check the compatibility of any libraries
you'll be using of course.

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


Re: Is python not good enough?

2010-01-13 Thread Chris Rebert
On Wed, Jan 13, 2010 at 1:06 AM, tanix ta...@mongo.net wrote:
 In article 
 53ec94c0-dbdd-4901-a46b-d7faee121...@j14g2000yqm.googlegroups.com, 
 johan.san...@gmail.com johan.san...@gmail.com wrote:
On Jan 13, 12:55=A0am, a...@pythoncraft.com (Aahz) wrote:
 In article 1b42700d-139a-4653-8669-d4ee2fc48...@r5g2000yqb.googlegroups.=
com,
 ikuta liu =A0ikut...@gmail.com wrote:

 Is python not good enough? for google, enhance python performance is
 the good way better then choose build Go language?

 It is not at all clear that -- despite some comments to the contrary --
 the Go developers are intending to compete with Python. =A0Go seems much
 more intended to compete with C++/Java. =A0If they're successful, we may
 eventually see GoPython. =A0;-)
 --
 Aahz (a...@pythoncraft.com) =A0 =A0 =A0 =A0 =A0 * =A0 =A0 =A0 =A0http:/=
/www.pythoncraft.com/

 If you think it's expensive to hire a professional to do the job, wait
 until you hire an amateur. =A0--Red Adair

GoPython i think would be neat.

 Well, as soon as they restore the braces to identify the code
 blocks and provide the functionality of advanced statically
 type languages, such as threads, async processing, all synchronization
 primitives, garbage collection, events and GUI, i'd be willing
 to switch to Python. Some of it is already there. But not all.

 Except, before doing it, I'd like to know what Python buys me
 compared to say Java.

The lack of knowledge shown here gives me even less confidence in your
Goldmine collections than before.

Cheers,
Chris
--
http://blog.rebertia.com

 --
 Programmer's Goldmine collections:

 http://preciseinfo.org

 Tens of thousands of code examples and expert discussions on
 C++, MFC, VC, ATL, STL, templates, Java, Python, Javascript, PHP,
 organized by major topics of language, tools, methods, techniques.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort list of dictionaries by key (case insensitive)

2010-01-13 Thread Chris Rebert
On Tue, Jan 12, 2010 at 11:45 PM, Nico Grubert nicogrub...@gmail.com wrote:
 Hi there

 I have the following list 'mylist' that contains some dictionaries:

 mylist = [{'title':'the Fog', 'id':1},
          {'title':'The Storm', 'id':2},
          {'title':'the bible', 'id':3},
          {'title':'The thunder', 'id':4}
         ]

mylist.sort(key = lambda d: d['title'])

Use operator.itemgetter() to optimize in the unlikely event it becomes
necessary.

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


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