Re: Screen scraper to get all 'a title' elements

2015-11-25 Thread TP
On Wed, Nov 25, 2015 at 12:42 PM, ryguy7272  wrote:
> Hello experts.  I'm looking at this url:
> https://en.wikipedia.org/wiki/Wikipedia:Unusual_place_names

Wildly offtopic but interesting, easy way to grab/analyze Wikipedia
data using F# instead of Python
http://evelinag.com/blog/2015/11-18-f-tackles-james-bond/

In your particular case something like:

open FSharp.Data
let [] wikiURL =
"https://en.wikipedia.org/wiki/Wikipedia:Unusual_place_names";
type PlaceNamesProvider = HtmlProvider

let placeNamesWiki = PlaceNamesProvider()
for row in placeNamesWiki.Tables.``Short & medium length names``.Rows do
  printfn "%s" row.Column1
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Trees

2015-01-20 Thread TP
On Mon, Jan 19, 2015 at 6:46 PM, Mark Lawrence 
wrote:

> I don't know if you've seen this http://kmike.ru/python-data-structures/
> but maybe of interest.
>

I haven't read but also possibly of interest:

Data Structures and Algorithms in Python by Michael T. Goodrich, Roberto
Tamassia, Michael H. Goldwasser (Wiley, 2013) [1]

Python Algorithms: Mastering Basic Algorithms in the Python Language, 2nd
Edition by Magnus Lie Hetland (Apress, 2014) [2]

[1] http://www.wiley.com/WileyCDA/WileyTitle/productCd-EHEP002510.html

[2] http://www.apress.com/9781484200568
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-27 Thread TP
On Tue, Nov 11, 2014 at 11:40 AM, Peter Cacioppi 
wrote:

> I get the impression that most Pythonistas aren't as habituated with
> assert statements as I am. Is that just a misimpression on my part? If not,
> is there a good reason to assert less with Python than other languages?
>
> As far as I can tell, Python supports assert perfectly well. When run with
> the optimization flagging, the asserts are truly removed.
>
> I think one needs to take care with some basic assert coding - it's not a
> substitute for unit tests, it doesn't absolve you of normal exception
> responsibilities, and, most of all, it should be used for passive
> inspection and not action. But given these guidelines, I still find it very
> useful as "active comments".
>

In "Why Most Unit Testing is Waste" by James O Coplien [1] he says on page
10:

"However, as with most unit tests, it's better to make this an assertion
than to pepper your test framework with such checks."

page 15:

"When I look at most unit tests -- especially those written with JUnit --
they are assertions in disguise. When I write a great piece of software I
sprinkle it with assertions that describe promises that I expect the
callers of my functions to live up to, as well as promises that function
makes to its clients. Those assertions evolve in the same artefact as the
rest of my code."

page 16:

"An even more professional approach is to leave the assertions in the code
when you ship, and to automatically file a bug report on behalf of the end
user and perhaps to try to re-start the application every time an assertion
fails."

"Turn unit tests into assertions. Use them to feed your fault-tolerance
architecture on high-availability systems. This solves the problem of
maintaining a lot of extra software modules that assess execution and check
for correct behavior; that's one half of a unit test. The other half is the
driver that executes the code: count on your stress tests, integration
tests, and system tests to do that."

And in "Seque" by James O Coplien [2] he is even more emphatic on page 17:

"This argumentation, of course, is just an alternative justification for
the use of assertions in the code, as we already introduced in Chapter 1.
Assertions are powerful unit-level guards that beat most unit tests in two
ways. First, each one can do the job of a large number (conceivably,
infinite) of scenario-based unit tests that compare computational results
to an oracle. Second, they extend the run time of the test over a much
wider range of contexts and detailed scenario variants by extending the
test into the lifetime of the product."

[1] http://www.rbcs-us.com/documents/Why-Most-Unit-Testing-is-Waste.pdf

[2] http://www.rbcs-us.com/documents/Segue.pdf
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python IDE.

2014-11-20 Thread TP
On Thu, Nov 20, 2014 at 11:29 AM, Irmen de Jong 
wrote:

> PyCharm *is* free, if you fall in one of several categories.
> See http://www.jetbrains.com/pycharm/buy/license-matrix.jsp
>
> Even when you have to buy it, it is cheap (IMO) for what it offers.
>

"PyCharm Editions Comparison" [1] is a better comparison between the
differences of the always free Community Edition and the Pro Edition of
PyCharm.

[1] https://www.
jetbrains.com/pycharm/features/editions_comparison_matrix.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-11 Thread TP
On Tue, Nov 11, 2014 at 11:40 AM, Peter Cacioppi 
wrote:

> I think one needs to take care with some basic assert coding - it's not a
> substitute for unit tests, it doesn't absolve you of normal exception
> responsibilities, and, most of all, it should be used for passive
> inspection and not action. But given these guidelines, I still find it very
> useful as "active comments".


I first came across asserts when using Wing IDE. See "Helping Wing Analyze
Code" [1] explains why using assert and isinstance will let Wing IDE
autocomplete things it otherwise couldn't.

PyCharm uses docstrings to accomplish the same task [2] but can also use
asserts/isinstance [3].

[1] https://wingware.com/doc/edit/helping-wing-analyze-code

[2] https://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html


[3]
http://stackoverflow.com/questions/9040387/is-there-a-way-to-explicitly-tell-pycharm-what-class-an-attribute-is-an-instance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Regex substitution trouble

2014-10-28 Thread TP
On Tue, Oct 28, 2014 at 4:02 AM,  wrote:

> Hi everyone,
>
> I'm not really sure if this is the right place to ask about regular
> expressions, but since I'm usin python I thought I could give a try :-)
> Here is the problem, I'm trying to write a regex in order to substitute
> all the occurences in the form $"somechars" with another string. This is
> what I wrote:
>
> newstring = re.sub(ur"""(?u)(\$\"[\s\w]+\")""", subst, oldstring)
>
> This works pretty well, but it has a problem, I would need it also to
> handle the case in which the internal string contains the double quotes,
> but only if preceeded by a backslash, that is something like
> $"somechars_with\\"doublequotes".
> Can anyone help me to correct it?
>
> Thanks in advance!
> --
> https://mail.python.org/mailman/listinfo/python-list
>

Carefully reading the Strings section of "Example Regexes to Match Common
Programming Language Constructs" [1] should (with a bit of effort), solve
your problem I think. Note the use of the negated character class for one
thing.

[1] http://www.regular-expressions.info/examplesprogrammer.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python and IDEs [was Re: Python 3 is killing Python]

2014-08-05 Thread TP
On Tue, Aug 5, 2014 at 12:25 PM, Duncan Booth 
wrote:

> So far they seem to have kept a pretty low profile; I suspect largely
> because until recently PTVS only worked with the pay versions of Visual
> Studio.
>

Not true. When it didn't work with the free express versions of VS, it
worked with the free Visual Studio Shell (that people have also not heard
about :) So there has always been some free way of running PTVS.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Windows Studio 2008 Download

2014-07-29 Thread TP
On Tue, Jul 29, 2014 at 5:54 AM, Colin J. Williams 
wrote:

> ii. The Service Pack 1 has the original studio as a prerequisite.  That is
> no longer available from Microsoft.


I haven't tried it but the Visual Studio 2008 Professional 90 Day Trial iso
*is* available from Microsoft at [1]. This doesn't show up by searching
download.microsoft.com. You have to stumble upon the link elsewhere. I
guess Microsoft *really* doesn't want people to use VS2008 anymore :)

[1]
http://download.microsoft.com/download/8/1/d/81d3f35e-fa03-485b-953b-ff952e402520/VS2008ProEdition90dayTrialENUX1435622.iso
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Windows Studio 2008 Download

2014-07-28 Thread TP
Hmmm. Now that I think about it the full Microsoft Visual Studio 2008
Service Pack 1 download I mentioned in my last email probably needs to have
Visual Studio 2008 already installed (it's been a number of years since I
had to install VS2008)? You could try it and see if it works.

If not download the free Express version I mentioned instead. Trying to
find the download link for the free VS2008 Express version is much harder
so I guess that's why people keep asking for it :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: .Net Like Gui Builder for Python?

2014-07-25 Thread TP
On Fri, Jul 25, 2014 at 7:40 PM, Chris Angelico  wrote:

> The OP asked for two things, which I'll separate because they're
> actually quite different.
>
> 1) Drag and drop widgets to create a window
> 2) Double-click a widget to edit its code (presumably event handler)
>
> I have used a number of GUI toolkits that did provide the first one,
> but the second is a lot more restrictive than you might think
>


Not that I disagree with the overall point of just using a text editor
(especially for Python GUIs) but apparently you've never created a C# WPF
app using Visual Studio? WPF fully supports layout controls, is *not*
generally pixel based it's more similar to HTML + CSS (although you do
pixel perfect layout if you try), and still easily does (2). And while I
almost exclusively use the Visual Studio XAML tab view rather than
bothering with the Designer view you can drag & drop if you really want to.
And Microsoft's Expression Blend takes that to a whole 'nother level
supposedly making it easy for "even" graphic designers to create GUIs
without delving too much into raw code wrangling.

One of the nice things about VIsual Studio and WPF (even in the XAML view)
is its Properties window. This lets you select a control and see all the
applicable possible properties and what legal choices you have for setting
them. This is an incredible aid to discovering how to use said controls.

And as far as any limitations of (2) goes, I still like using the Events
view of the Properties window to initially hook up an event handler. This
automatically creates a  "correctly" (or at least consistently) named and
argumented event handler and adds the proper attribute to the XAML. It is
easy enough to then mess around with the generated code if that doesn't
quite suit your needs. Having the list of possible event handlers all in
one place instead of having to look up the doc is invaluable. And being
able to press F1 just about anywhere and have the relevant document open up
is even more so.

As far as I've seen Visual Studio + WPF really is state of the art for GUI
building. I wish more developers were familiar with all its capabilities so
they could know what to whine for in their own programming environment :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python and IDEs [was Re: Python 3 is killing Python]

2014-07-19 Thread TP
On Sat, Jul 19, 2014 at 12:28 AM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> For Python users, the IDEs from
> Wingware and Activestate are notable:
>
> https://wingware.com/
> http://komodoide.com/
>

I would say that since PyCharm (https://www.jetbrains.com/pycharm/) now has
a free Community Edition it is an even more notable IDE as the above two
programs cost $.

And as a Windows user, for version control I really like TortoiseHg (
http://tortoisehg.bitbucket.org/) for Mercurial. Likewise I tend to use
TortoiseSVN and TortoiseGit rather than the command line. PyCharm even has
support for those but I still like right-clicking on folders in Windows
Explorer and activating various hg commands from the popup menu. Especially
since not every program I write is written in Python :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Editor for Python

2014-01-09 Thread TP
On Friday, 23 November 2001 04:13:40 UTC+5:30, MANUEL FERNANDEZ PEREZ
 wrote:

> > Hello,
> > I'm looking for an editor for Python.I' m interested it works on
> Windows.Can
> > anybody help me?
>
It's an IDE rather than "just" an editor but how about PyCharm 3 Community
Edition? [1]

[1] https://www.jetbrains.com/pycharm/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Download Visual Studio Express 2008 now

2013-08-29 Thread TP
On Thu, Aug 29, 2013 at 2:43 AM, Philip Inglesant  wrote:

> Hi Martyn,
>
> Thanks for the good advice to download VS 2008 before M$ delete it from
> their download servers.
>
> Unfortunately they have already done this so many Python modules now can't
> be compiled correctly on Windows!
>
> Best regards,
>
> Philip
> --
> http://mail.python.org/**mailman/listinfo/python-list
>

Not true.

See

http://stackoverflow.com/questions/15318560/visual-c-2008-express-download-link-dead
for still live link to VS2008 Express SP1 iso at

http://download.microsoft.com/download/E/8/E/E8EEB394-7F42-4963-A2D8-29559B738298/VS2008ExpressWithSP1ENUX1504728.iso
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My son wants me to teach him Python

2013-06-13 Thread TP
On Wed, Jun 12, 2013 at 1:02 PM, Chris Angelico  wrote:

> I put the question to the
> list, and got back a number of excellent and most useful answers
> regarding book recommendations, and we ended up going with (if memory
> serves me) Think Python [1]
>

Here's a link [1] to Chris' original question (and the following answers
including mine which mentioned Think Python).

Chris' requirements were slightly different. In your case "Python for Kids
- A Playful Introduction to Programming" [2] might be more appropriate as a
first book. Despite the title it covers a wide range of topics
*specifically geared towards writing a game in Python*. See the detailed
table of contents to help decide.

Also Chris has an "unnatural" abhorrence of Python 2.7 :) --- at least as
far as learning Python books. As such he dismissed too early what I think
might be a great initial (or 2nd) book, Hello Python [3]. To requote the
Preface which resonates at least with me:

"I thought back to how I first learned to program. I didn't read an
entire programming book from cover to cover and then write a program
after I knew everything there was to know. Instead I started with a
goal, something that I wanted to do, and worked toward it, figuring
things out as I went. I read programming books from time to time,
but really only to figure out the bits I was stuck on. When I was
done, my programs weren't particularly elegant or fast, but they
were mine---I knew how they worked, and they solved a real problem
that I was having."

Some chapter titles include "Gaming with Pyglet", "Twisted Networking"
(which implements a MUD), and "Django" so it covers quite a bit of ground.
Again see the detailed table of contents.

Notice that the subtitle for Think Python [4] is "How to Think Like a
Computer Scientist" which is not every beginning programmer's goal. Yes,
Think Python is free, and yes it's probably quite good, but it's not for
everyone. In particular the presentation is a lot drier than the above
mentioned books.

Somewhat offtopic but mentioned in the thread: Here's what Elliotte Rusty
Harold had to say about Java Console IO in Java I/O, 2nd Edition (OReilly,
2006) which I recently read while helping somewith with their college Java
(yuck!) homework:

Many common misconceptions about I/O occur because most programmers'
first exposure to I/O is through the console. The console is
convenient for quick hacks and toy examples commonly found in
textbooks, and I will use it for that in this book, but it's really
a very unusual source of input and destination for output, and good
Java programs avoid it. It behaves almost, but not completely,
unlike anything else you'd want to read from or write to. While
consoles make convenient examples in programming texts like this
one, they're a horrible user interface and really have little place
in modern programs. Users are more comfortable with a well-designed
GUI. Furthermore, the console is unreliable across platforms. Many
smaller devices such as Palm Pilots and cell phones have no
console. Web browsers running applets sometimes provide a console
that can be used for output. However, this is hidden by default,
normally cannot be used for input, and is not available in all
browsers on all platforms.

Yikes, a bit opinionated isn't he? Reminds me of some people on this list :)

Finally, regarding sneering at HTML/Javascript. While I've never used the
technology, HTML5/Javascript has the Canvas and possibly WebGL. I've
noticed all sorts of new books on the topic, for example:

Core HTML5 Canvas  Graphics, Animation, and Game Development (Prentice
Hall, 2012)

HTML5 Games Development by Example - Beginner's Guide (Packt, 2011)

HTML5 Games Most Wanted (Friends of Ed, 2012)

Supercharged JavaScript Graphics - With HTML5 Canvas, jQuery, and More
(O'Reilly, 2011)

HTML5 Graphics and Data Visualization Cookbook (Packt, 2012)

This in fact "may" be/is the future of graphics programming (at least in
terms of # of apps written)? And TypeScript [5] "may" make using javascript
(under the hood) less objectionable.

I still agree with your overall approach, learn programming via Python
first --- not for god's sake Java, which colleges still think is the bee's
knees :). But realize that it's only one tool in the programmer's toolkit
and you'll eventually have to learn many languages.

[1] http://mail.python.org/pipermail/python-list/2013-May/646208.html

[2] http://nostarch.com/pythonforkids

[3] http://www.manning.com/briggs/

[4] http://www.greenteapress.com/thinkpython/thinkpython.html

[5] http://www.typescriptlang.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python teaching book recommendations: 3.3+ and with exercises

2013-05-03 Thread TP
[Just a note, all the book links in my original post have complete table of
contents listing, so don't just take my word on their suitability.]

Here's some
I missed:

Programming in Python 3, 2nd Edition - Mark Summerfield (Addison-Wesley,
2009) [1a]. Exercises. Solutions available online. At a quick glance I'd
say the exercises are also better for the beginner. Less of a computer
science orientation?

Learning Python, 4th Edition, Mark Lutz (Oreilly,2009) [1]. The 5th edition
[2] is supposed to come out in June. Python 2.6 & 3.x. Has exercises at the
end of every Part and answers in Appendix B. Also has "Test Your Knowledge"
quizzes & answers. 1200+ pages! Too overwhelming for a first Python book?
Ideal for a 2nd or 3rd however.

After seeing your response, I'd say, just one book isn't really going to
work. So I would recommend:

1) Quickly go through Python for Kids. While it may say it's for kids, it
actually covers quite a bit of ground (including writing a game using
tkinter). I doubt it's so easy as to be boring. The lazy can also download
sample code and solutions to the Programming Puzzles from the webpage.

2) Then Summerfield's Programming in Python 3. It has a lot more detail and
also
spends time on the Python Standard Library.

Or maybe Think Python. A *lot* drier presentation than Python for Kids --
after all, the subtitle which I forgot to mention is "How to Think Like a
Computer Scientist". Newer than Summerfield
, but only 1/3 the length
. Since I've only skimmed both I find it hard to recommend one over the
other.

3) Finally, when he *really* wants to learn all the gory details about
Python programming, tackle Learning Python (and by that time hopefully the
5th edition will be out).

Once you've "learned"
P
ython then I would also recommend Programming Python, 4e - Mark Lutz
(Oreilly,2010) [3] for detailed info on using some of the standard modules.
Also Python Cookbook: Recipes for Mastering Python 3 - Beazley & Jone
(OReilly, 2013) [4].

[Off Topic] 

Depending on his age and what else he is learning at school, I also kinda
think NumPy/SciPy/Matplotlib can be very enlightening.

SciPy and NumPy - E. Bressert (O'Reilly, 2013) [5]. A brief overview.

NumPy 1.5 Beginner's Guide - I. Idris (Packt, 2011) [6]

NumPy Cookbook - I. Idris (Packt, 2012) [7]

Already started back in February and ending in a month, there is MIT's free
online
video
edX course "6.00x: Introduction to Computer Science and Programming" [8]
which uses Python 2.7 and the book "Introduction to Computation and
Programming Using Python (Spring 2013 edition)" by John Guttag [9]. This is
also viewable free online if you are registered for the course. Estimated
effort 12 hours/week, eeek!


[1a] http://www.qtrac.eu/py3book.html

[1] http://shop.oreilly.com/product/9780596158071.do

[2] http://shop.oreilly.com/product/0636920028154.do

[3] http://shop.oreilly.com/product/9780596158118.do

[4] http://shop.oreilly.com/product/0636920027072.do

[5] http://shop.oreilly.com/product/0636920020219.do

[6]
http://www.packtpub.com/numpy-1-5-using-real-world-examples-beginners-guide/book

[7] http://www.packtpub.com/numpy-for-python-cookbook/book

[8] https://www.edx.org/courses/MITx/6.00x/2013_Spring/about

[9]
http://mitpress.mit.edu/books/introduction-computation-and-programming-using-python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python teaching book recommendations: 3.3+ and with exercises

2013-05-02 Thread TP
On Thu, May 2, 2013 at 7:36 AM, Chris Angelico  wrote:

> One of my younger brothers, still school age, is to be studying some
> aspect of computing for the next term or two. I strongly recommended
> he learn Python (it has a bit more future than studying the internals
> of OS/2), and my/his father then asked me what book I'd recommend him
> to study through. I know this has come up a few times, but searching
> back in my emails didn't give a clear answer.
>
> Whether it's an ebook or in paper doesn't matter, but there need to be
> exercises that the student can perform on his own, and then an
> external tutor (aka my dad) then check up on. Python 3 is a must;
> preferably something designed for 3.3+ as that's what he'll be using.
> Beyond that, I was just asked to recommend "the best", which is
> unfortunately vague... but I gather they'll be deferring to the
> expertise of the list in figuring out what that means :)
>
> So, within those not-very-many restrictions, what would you all
> recommend? Let's get a nice discussion going and see where it leads us
> (most likely to a resident troll ranting about a favorite topic, but
> hey, maybe Dihedral will come out with some nugget of wisdom for us)!
>

Since I've been using Python for years, I've only skimmed new books.
Personally, I found the standard Python tutorial [1] (and reading the
What's New sections) more than adequate for originally learning Python.

Anyway, given your constraints, here's what I've come up with (stipulating
Python 3, limits the number of available books. And requiring exercises is
even stricter):

Python for Kids - A Playful Introduction to Programming - J. Briggs (No
Starch, 2013) [2]. Python 3.2? Not necessarily just for kids but definitely
slanted towards younger readers. Has "Programming Puzzles".

Think Python - A. Downey (O'Reilly, 2012) [3]. For Python 2 & 3. Exercises
but no answers? There is also a Python 3 specific version available. Free.

Beginning Python - Using Python 2.6 and Python 3.1 - J. Payne (Wrox, 2010)
[4]. Has exercises but... they seem a bit simplistic to me. Answers in
Appendix A.

Head First Python - Barry (OReilly,2011) [5] Python 3. Says for people who
already know another language (and I would have to agree with that).
Exercises.

Introduction to Programming Using Python - Y. Liang (Pearson, 2013) [6]. A
bit dull looking. Probably a college textbook? Lots of exercises. Author
also has similar books on C++ & Java. Expensive.

Ignoring the constraints, here's another one that looks really interesting:

Hello Python - A. Briggs (Manning, 2012) [7]. Python 2 only. Learn by
incrementally writing and improving working programs. Less focused on
syntax and more on getting the job done. No exercises per se, but since
goal is working programs, progress can be still be checked. More about the
"batteries" (including somewhat surprisingly pyglet, twisted & django).

From the Preface:

"I thought back to how I first learned to program. I didn't read an
entire programming book from cover to cover and then write a program
after I knew everything there was to know. Instead I started with a
goal, something that I wanted to do, and worked toward it, figuring
things out as I went. I read programming books from time to time,
but really only to figure out the bits I was stuck on. When I was
done, my programs weren't particularly elegant or fast, but they
were mine---I knew how they worked, and they solved a real problem
that I was having."

Page 9:

"We'll be using the latest version of Python 2, because most of the
libraries that we'll use in this book don’t yet support Python 3."

[1] http://docs.python.org/3/tutorial/index.html

[2] http://nostarch.com/pythonforkids

[3] http://www.greenteapress.com/thinkpython/thinkpython.html

[4]
http://www.wrox.com/WileyCDA/WroxTitle/Beginning-Python-Using-Python-2-6-and-Python-3-1.productCd-0470414634.html

[5] http://shop.oreilly.com/product/0636920003434.do

[6]
http://www.pearsonhighered.com/educator/product/Introduction-to-Programming-Using-Python/9780132747189.page

[7] http://www.manning.com/briggs/
-- 
http://mail.python.org/mailman/listinfo/python-list


using "*" to make a list of lists with repeated (and independent) elements

2012-09-26 Thread TP
Hi everybody,

I have tried, naively, to do the following, so as to make lists quickly:

>>> a=[0]*2
>>> a
[0, 0]
>>> a[0]=3
>>> a
[3, 0]

All is working fine, so I extended the technique to do:

>>> a=[[0]*3]*2
>>> a
[[0, 0, 0], [0, 0, 0]]
>>> a[0][0]=2
>>> a
[[2, 0, 0], [2, 0, 0]]

The behavior is no more expected!
The reason is probably that in the first case, 0 is an integer, not a list, 
so Python copies two elements that are independent.
In the second case, the elements are [0,0,0], which is a list; when Python 
copies a list, he copies in fact the *pointer* to the list, such that we 
obtain this apparently strange behavior.

Is it the correct explanation?
In these conditions, how to make this list [[0,0,0],[0,0,0]] with "*" 
without this behavior?

Thanks,

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


Re: Is the Usenet to mailing list gateway borked?

2011-07-01 Thread TP
On Thu, Jun 30, 2011 at 11:41 AM, Thomas 'PointedEars' Lahn
 wrote:
> Thomas Guettler wrote:
>
>> On 30.06.2011 03:24, Thomas 'PointedEars' Lahn wrote:
>>> Andrew Berg wrote:
>>>> […]
>>>
>>> As for your question in the Subject, I do not know since I am reading the
>>> newsgroup.
>>>
>>> Therefore, however, I can tell you that the mailing list to Usenet
>>> gateway is seriously borked, as missing References header fields are not
>>> generated by the gateway.  As a result, there are few if any threads left
>>> in the newsgroup, which makes it an increasing PITA to read.  (And no,
>>> threading by Subject is a stupid idea.)
>>>
>>> Would someone responsible *please* fix this?  I am willing to provide
>>> assistance, see also my suggestion in
>>> <news:5337093.9j7nak4...@pointedears.de>.
>>
>> Who is responsible?
>
> If I knew that I would not ask here.
>
>> I think in the past there were not many broken threads. I wonder what
>> changed this.
>
> One factor, as I see it, is an increasing number of people using e-mail
> clients that do not generate the References header field, as it is only a
> SHOULD, not a MUST per RFC 5322, or people using mail clients that are FUBAR
> (like G2, Google Groups and Mail).  But that header field is mandatory for
> Network News (RFC 5536), and if it is missing you create a mess for
> newsreaders (applications and people alike).  "Bugs" making a slumbering
> real bug in the gateway implementation apparent.
>
> But that appears to be only half the truth as e.g. I can retrieve none of
> the messages that  of
> 15:19 GMT+02:00 today refers to, regardless from where they supposedly
> originated.  I am not deleting messages locally and I have a rather fast and
> reliable newsfeed, so the messages should have arrived by now.
>
> --
> PointedEars
>
> Bitte keine Kopien per E-Mail. / Please do not Cc: me.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Not sure if this is relevant. I use mail.google.com to follow mailing
lists and a large proportion of python-list traffic ends up in my
gmail spam folder for some reason?

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


Re: Python IDE/text-editor

2011-04-16 Thread TP
On Sat, Apr 16, 2011 at 2:32 AM, jacek2v  wrote:
> On Apr 16, 11:18 am, Daniel Kluev  wrote:
>> > Please continue your recommendations.
>>
>> WingIDE has all that and much more, if you are willing to consider
>> non-free IDE.
>> Its multi-threading debugger definitely worth the cost of Pro version for me.
>
> I confirm :)
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I normally use emacs for basic text editing, tried Komodo, Eric, and
IDLE but prefer WingIDE when writing Python code. In particular, the
debugger is really nice. (Of course I also like Visual Studio when
writing/debugging C/C++/C# so maybe I'm just weird).

A new non-free up-and-comer to consider is JetBrain's PyCharm.

And there is PyDev for Eclipse (but I personally tend to avoid Java
based programs).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use the Source Luke

2011-01-29 Thread TP
On Fri, Jan 28, 2011 at 10:32 AM, Raymond Hettinger  wrote:
> I hoping a new trend will start with dev's putting direct
> source code links in their documentation:
>
>  http://rhettinger.wordpress.com/2011/01/28/open-your-source-more/
>
> I'm looking for more examples of projects that routinely
> link their docs back into relavant sections of code.
> Have any of you all seen other examples besides
> the Go language docs and the Python docs?
>
>
> Raymond
> --
> http://mail.python.org/mailman/listinfo/python-list
>

The Sphinx Python Documentation Generator
(http://sphinx.pocoo.org/index.html), used for documenting lots of
things other than Python, has an extension called "sphinx.ext.viewcode
– Add links to highlighted source code"
(http://sphinx.pocoo.org/ext/viewcode.html).

You can see my use of it here on a small PyQt project:
http://tpgit.github.com/MDIImageViewer/imageviewer.html. You can even
view the Sphinx documentation "code" by clicking the "Show Source"
link on the left.

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


Re: list parameter of a recursive function

2010-10-07 Thread TP
Seebs wrote:

> On 2010-10-07, TP  wrote:
>> Diez B. Roggisch wrote:
>>> A safer alternative for these cases is using tuples, because they are
>>> immutable.
> 
>> The problem with tuples is that it is not easy to modify them:
> 
> This is probably the best post-and-response I've seen in the last couple
> of months.

:-) Yes, they are immutable. I badly expressed the fact that the facilities 
of lists to create new lists are not available with tuples.

But my sentence was funny, I have to admit it :-) I hope that this 
conversation will not be included in the "fortunes"!!

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list parameter of a recursive function

2010-10-06 Thread TP
Steven D'Aprano wrote:

>> I think I prefer doing an explicit copy.copy, because it allows to
>> remind the reader that it is very important to take care of that.
> 
> I think a comment is better for that. It's better to explicitly say
> something is important than to assume the reader will guess.

Yes, you are right.

> Besides, what if the caller wants to supply their own list, and they
> *want* it modified in place rather than a copy made? (I have no idea why
> they might want this, but anything is possible...) You should avoid
> making copies except in methods that are *for* making copies.

My function gives a sensible result only if the list is not modified in 
place. In fact, this list is only used internally for the recursion. That is 
why I have made this function "private":

def __relation_loop( sqlite_cursor
, table_name
, crossed_tables = None
, previous_step_link = None
, onetomany_allowed_depth = 1 ):

I give to the user (me!) only access to the public function:

def relation_loop( sqlite_cursor
, table_name
, onetomany_allowed_depth = 1 ):

return __relation_loop( sqlite_cursor
, table_name
, crossed_tables = None
, previous_step_link = None
, onetomany_allowed_depth = onetomany_allowed_depth )

So, crossed_tables and previous_step_link, are only used by the recursion 
process, they are not accessible to the user.

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list parameter of a recursive function

2010-10-06 Thread TP
Diez B. Roggisch wrote:

> Back to your example: your solution is perfectly fine, although a bit
> costly and more error-prone if you happen to forget to create a copy.
> A safer alternative for these cases is using tuples, because they are
> immutable.

Thanks Diez for your explanation.
The problem with tuples is that it is not easy to modify them: in my case, I 
need to append a string to the tuple at each recursive step.
So, it seems to me that I need to write a loop to modify the tuple, because 
on a simple example:

>>> a=("foo", "bar")
>>> b=(a[0],a[1],"toto")
>>> b
(u'foo', u'bar', u'toto')

I do not find any other means to obtain that result for b. With lists, I can 
use ".extend()".
Am I right?


-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list parameter of a recursive function

2010-10-06 Thread TP
Chris Torek wrote:

>>import copy from copy
> 
> [from copy import copy, rather]

Yes, sorry.

> Note that if f() is *supposed* to be able to modify its second
> parameter under some conditions, you would want to make the copy
> not at the top of f() but rather further in, and in this case,
> that would be trivial:
> 
> def f(arg, some_list = None):
> if some_list is None:
> some_list = []
> ...
> if some_condition:
> # make copy of list and append something
> f(new_arg, some_list + [elem])
> elif other_condition:
> # continue modifying same list
> f(new_arg, some_list)

Thanks a lot Chris!
I think I prefer doing an explicit copy.copy, because it allows to remind 
the reader that it is very important to take care of that. But your trick is 
very interesting also.

Cheers,

Julien


-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
-- 
http://mail.python.org/mailman/listinfo/python-list


list parameter of a recursive function

2010-10-06 Thread TP
Hi,

I have a function f that calls itself recursively. It has a list as second 
argument, with default argument equal to None (and not [], as indicated at:
http://www.ferg.org/projects/python_gotchas.html#contents_item_6 )

This is the outline of my function:

def f ( argument, some_list = None ):

   if some_list == None:
  some_list = []
   [...]
   # creation of a new_argument
   # the function is called recursively only if some condition is respected
   if some_condition:
  some_list.append( elem )
  f( new_argument, some_list )
   # otherwise, we have reached a leaf of the a branch of the recursive tree
   # (said differently, terminal condition has been reached for this branch)
   print "Terminal condition"

The problem is that when the terminal condition is reached, we return back 
to some other branch of the recursive tree, but some_list has the value 
obtained in the previous branch!
So, it seems that there is only one some_list list for all the recursive 
tree.
To get rid of this behavior, I have been compelled to do at the beginning of 
f:

import copy from copy
some_list = copy( some_list )

I suppose this is not a surprise to you: I am compelled to create a new 
some_list with the same content.
So, if I am right, all is happening as if the parameters of a function are 
always passed by address to the function. Whereas in C, they are always 
passed by copy (which gives relevance to pointers).

Am I right?

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
-- 
http://mail.python.org/mailman/listinfo/python-list


adding a method to an existing builtin class

2010-09-26 Thread TP
Hi everybody,

Today I have learned a bit of the news of Python 3.0 compared to 2.4 
version.

By the way, I have asked myself if it is possible to add a method to a 
builtin type as 'unicode':

>>> a="foo"
>>> type(a)

>>> print(dir(a))
['__add__', ..., 'zfill']

For example, I would like to add a "colorize" method to 'unicode' objects. 
Is this possible?
Or am I compelled to derive the unicode builtin as below:

class my_unicode(unicode):
   def __init__( self, unicode_string ):
 super( my_unicode, self ).__init__(  )
   def colorize( self ):
   return "\x1b[93;102m" + self + "\x1b[0m"

my_unicode_string = my_unicode( "coucou" )
print( type( my_unicode_string ) )
print( my_unicode_string.colorize() )
print( my_unicode_string.upper() )

Thanks,

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: equivalent of bash "set -x" in Python

2010-09-26 Thread TP
James Mills wrote:

> What do you mean by "command" ?

For example, print statements, but it could extend to class definitions, 
etc. I am going to examine the solution given by Chris.

Cheers,
Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
-- 
http://mail.python.org/mailman/listinfo/python-list


equivalent of bash "set -x" in Python

2010-09-26 Thread TP
Hi everybody,

I am interested in having the possibility to print every Python commands in 
a script (for didactic purpose).
So I am looking for some sort of equivalent of bash "set -x".
Does it exist?

Thanks

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: highlight words by regex in pdf files using python

2010-03-18 Thread TP
On Wed, Mar 17, 2010 at 7:53 AM, Peng Yu  wrote:
> On Tue, Mar 16, 2010 at 11:12 PM, Patrick Maupin  wrote:
>> On Mar 4, 6:57 pm, Peng Yu  wrote:
>>> I don't find a general pdf library in python that can do any
>>> operations on pdfs.
>>>
>>> I want to automatically highlight certain words (using regex) in a
>>> pdf. Could somebody let me know if there is a tool to do so in python?
>>
>> The problem with PDFs is that they can be quite complicated.  There is
>> the outer container structure, which isn't too bad (unless the
>> document author applied encryption or fancy multi-object compression),
>> but then inside the graphics elements, things could be stored as
>> regular ASCII, or as fancy indexes into font-specific tables.  Not
>> rocket science, but the only industrial-strength solution for this is
>> probably reportlab's pagecatcher.
>>
>> I have a library which works (primarily with the outer container) for
>> reading and writing, called pdfrw.  I also maintain a list of other
>> PDF tools at http://code.google.com/p/pdfrw/wiki/OtherLibraries  It
>> may be that pdfminer (link on that page) will do what you want -- it
>> is certainly trying to be complete as a PDF reader.  But I've never
>> personally used pdfminer.
>>
>> One of my pdfrw examples at http://code.google.com/p/pdfrw/wiki/ExampleTools
>> will read in preexisting PDFs and write them out to a reportlab
>> canvas.  This works quite well on a few very simple ASCII PDFs, but
>> the font handling needs a lot of work and probably won't work at all
>> right now on unicode.  (But if you wanted to improve it, I certainly
>> would accept patches or give you commit rights!)
>>
>> That pdfrw example does graphics reasonably well.  I was actually
>> going down that path for getting better vector graphics into rst2pdf
>> (both uniconvertor and svglib were broken for my purposes), but then I
>> realized that the PDF spec allows you to include a page from another
>> PDF quite easily (the spec calls it a form xObject), so you don't
>> actually need to parse down into the graphics stream for that.  So,
>> right now, the best way to do vector graphics with rst2pdf is either
>> to give it a preexisting PDF (which it passes off to pdfrw for
>> conversion into a form xObject), or to give it a .svg file and invoke
>> it with -e inkscape, and then it will use inkscape to convert the svg
>> to a pdf and then go through the same path.
>
> Thank you for your long reply! But I'm not sure if you get my question or not.
>
> Acrobat can highlight certain words in pdfs. I could add notes to the
> highlighted words as well. However, I find that I frequently end up
> with highlighting some words that can be expressed by a regular
> expression.
>
> To improve my productivity, I don't want do this manually in Acrobat
> but rather do it in an automatic way, if there is such a tool
> available. People in reportlab mailing list said this is not possible
> with reportlab. And I don't see PyPDF can do this. If you know there
> is an API to for this purpose, please let me know. Thank you!
>
> Regards,
> Peng
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Take a look at the Acrobat SDK
(http://www.adobe.com/devnet/acrobat/?view=downloads). In particular
see the Acrobat Interapplication Communication information at
http://www.adobe.com/devnet/acrobat/interapplication_communication.html.

"Spell-checking a document" shows how to spell check a PDF using
visual basic at
http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Acrobat9_HTMLHelp&file=IAC_DevApp_OLE_Support.100.17.html

"Working with annotations" shows how to add an annotation with visual
basic at 
http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Acrobat9_HTMLHelp&file=IAC_DevApp_OLE_Support.100.16.html.

Presumably combining the two examples with Python's win32com should
allow you to do what you want.
-- 
http://mail.python.org/mailman/listinfo/python-list


Am I using ctypes correctly? Where are fprints going?

2010-02-15 Thread TP
>From the Cplusplus-sig, I gathered that instead of Boost.Python I
should use ctypes for the following problem. But let me make sure I'm
using it correctly.

I am calling the C Leptonica Image Processing C Library
(http://leptonica.com) from python.

Within its leptprotos.h file are functions like this:

 extern PIX * pixRead ( const char *filename );
 extern void pixDestroy ( PIX **ppix );

Using Windows XP, and within a Command Prompt I do this:

python26
>>> import ctypes
>>> leptonica = ctypes.cdll.leptonlib
>>> pixRead = leptonica.pixRead

>>> pix=ctypes.c_void_p()
>>> pix.value = pixRead(r"test.tif")
>>> pix
c_void_p(12310144)

>>> leptonica.pixGetWidth(pix)
1553   #this is the correct width

>>> leptonica.pixDestroy(ctypes.byref(pix))
>>> pix
c_void_p(None)   #This look right, pixDestroy() sets the pointer to NULL.

Is this the proper way you are supposed to supply the address of a
pointer that is returned by a C function? Is there a better way?

Should I have done the following also?

>>> pixRead.restype = ctypes.c_void_p
>>> pixDestroy.restype = None

Now that the pix has been destroyed, you shouldn't be able to get its width:

>>> leptonica.pixGetWidth(pix)
-1

This is correct but there also should have been an error message printed out.

The C library is doing this (I think, I haven't actually used the
debugger on it):

sprintf(charbuf, "Error in %s: %s\n", procname, msg);
fprintf(stderr, charbuf, ival);

But I don't see any error message appear in my console window?

Finally, the documentation states for ctypes.util.find_msvcrt():

  Windows only: return the filename of the VC runtype library used by
  Python, and by the extension modules. If the name of the library
  cannot be determined, None is returned.

  If you need to free memory, for example, allocated by an extension
  module with a call to the free(void *), it is important that you use
  the function in the same library that allocated the memory.

>>> import ctypes.util
>>> ctypes.util.find_msvcrt()
'msvcr90.dll'

Does this mean that if I build a Debug version of the Leptonica DLL
(which will use the Debug version of the runtime library,
msvcr90d.dll), that I also have to build and use a Debug version of
Python26?

I tried using leptonlibd.dll with the ActiveState release version of
Python26 and didn't see any immediate error.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: intricated functions: how to share a variable

2009-08-05 Thread TP
Bearophile wrote:

> So probably a better solution is to just use the normal function
> semantics: you pass them an argument and you take an argument as
> return value. Such return value will be the new version of the value
> you talk about.

Thanks for your answer.
Yes, it is better like this. My problem is that I cannot get the return
values of the function and affect it to some variable, because the function
is called via a "signal-slot" connection of PyQt4, not by an explicit
inline function call.

For example:
#
def tutu():

def toto():

print a
a = 4
print a

a=2

# ...
# definition of some graphical QPushButton "button"
# ...
# ...

self.connect( button, SIGNAL( "clicked" ), toto )

tutu()
##

Then, as advised Diez, perhaps the best solution is to have "true" global
variables by using a class and defining the variable a as a member self.a
of the class. By doing like this, a will be known everywhere.

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
-- 
http://mail.python.org/mailman/listinfo/python-list


intricated functions: how to share a variable

2009-08-05 Thread TP
Hi everybody,

See the following example:

#
def tutu():

def toto():

print a
a = 4
print a

a=2
toto()

tutu()
##

I obtain the following error:
"UnboundLocalError: local variable 'a' referenced before assignment"

This is because Python looks in the local context before looking in the
global context.

The use of "global a" in toto() does not help because global allows to force
Python to look for the variable at the module level.

So, how to share a variable between intricated functions?

Thanks a lot

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get back an object from its id() value

2009-04-08 Thread TP
MRAB wrote:

> You could create a dict with the string as the key and the object as the
> value.

Thanks. But it implies an additional data structure: a dictionnary.
I don't know what is the best:
* using an additional dict and maintaining it
* or using the "di" module proposed by CTO

If "di" is reliable, it seems a good solution for my initial constraint
which is the impossibility to store anything but strings in my data
structure.

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


how to get back an object from its id() value

2009-04-08 Thread TP
Hi everybody,

I have a data structure (a tree) that has one constraint: I can only store
strings in this data structure.

To know if an object foo already exists in memory, I store "str(id(foo))" in
the data structure.
OK.

But how do I get a usable reference from the id value?
For example, if "foo" has a method "bar()", how can I call "foo.bar()"
from "str(id(foo))" (say, 149466208).

Thanks in advance,

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


double/float precision question

2009-04-01 Thread TP
Hi everybody,

Try the following python statements:

>>> "%.40f" % 0.222
'0.098864108374982606619596'
>>> float( 0.222)
0.1

It seems the first result is the same than the following C program:

#include 

int main(void)
{
double a = 0.222;

printf( "%.40f\n", a );
return 0;
}
#

My problem is the following:
* the precision "40" (for example) is given by the user, not by the
programmer.
* I want to use the string conversion facility with specifier "e", that
yields number is scientific format; so I cannot apply float() on the result
of "%.40e" % 0.222, I would lost the scientific
format.

Is there any means to obtain the full C double in Python, or should I limit
the precision given by the user (and used in "%.*e") to the one of a Python
float?

Thanks in advance

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: modifying a list element from a function

2009-03-30 Thread TP
Adrian Dziubek wrote:

> Could you explain your high level goal for this? It looks like a very
> wicked way of doing things. Have You tried to read the list methods'
> documentation? Maybe there you find something you need (like
> list.index)?

Hello,

I have a "disambiguation" function that modifies a text
contained "somewhere" in each element of a list. The way this text is
accessed by the function should depend on an external accessor, or setter,
so that any list could be processed, in a generic way.

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


modifying a list element from a function

2009-03-27 Thread TP
Hi everybody,

Be a the following list, containing list elements which second field is a
string.

>>> a = [ [4, "toto"], [5, "cou"] ]
>>> a[0][1]="tou"
>>> a
[[4, 'tou'], [5, 'cou']]

OK.

Now, I want:
* to do the same modification on the list "a" within a function
* not to hardcode in this function the position of the string in each
element of a.

At first sight, we think at defining a function like this:

def assign( text_accessor, list_elem, new_textvalue ):

text_accessor( list_elem ) = new_textvalue

and then doing:

assign( lambda elem: elem[1], a[0], "co" )

But it does not work, we obtain:

text_accessor( list_elem ) = new_textvalue
SyntaxError: can't assign to function call

In fact, we should work on the address of text_accessor( list_elem ). How to
do that?

Thanks

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


context not cleaned at the end of a loop containing yield?

2009-03-26 Thread TP
Hi everybody,

This example gives strange results:


def foo( l = [] ):

l2 = l
print l2
for i in range(10):
if i%2 == 0:
l2.append( i )
yield i


>>> [i for i in ut.foo()]
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [i for i in ut.foo()]
[0, 2, 4, 6, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [i for i in ut.foo()]
[0, 2, 4, 6, 8, 0, 2, 4, 6, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
...

How to explain this behavior? Why l is not [] when we enter again the
function foo()?

Thanks

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to prevent python import from looking into the current directory

2009-03-06 Thread TP
Benjamin Peterson wrote:

> While the solutions given by others in this thread will work, I think it
> is best policy to not name your own modules after stdlib ones. When I see
> "os" referenced in code, I assume it is the stdlib one, and don't want to
> be confused by the presence of your own module.

Yes, I have finally chosen this alternative: things are much simpler like
this.
Thanks

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to prevent python import from looking into the current directory

2009-03-06 Thread TP
Ben Finney wrote:

> (Could you please set a valid email address for people to contact you
> if necessary?)

Thanks a lot for your help.
My email address is in my signature:

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


how to prevent python import from looking into the current directory

2009-03-06 Thread TP
Hi everybody,

I would like to prevent the loading of modules in the current directory.
For example, if I have a personal module in the current directory
named "os", when I do "import os", I would like Python to import os
standard module, not my personal module of the current directory.
Is this possible?

Thanks
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


distutils: "build" command

2009-03-05 Thread TP
Hi everybody,

I have programmed a python package, and I would like to use distutils with
it. My package has the following structure after doing sdist and build:

$ python setup.py sdist
[...]
$ python setup.py build
[...]
$ tree
.
|-- MANIFEST
|-- MANIFEST.in
|-- README
|-- build
|   `-- lib
|   `-- utils
|   |-- __init__.py
|   `-- __init__.pyc
|-- dist
|   `-- utils-1.0.tar.gz
|-- utils
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- utils_1
|   |   |-- __init__.py
|   |   |-- __init__.pyc
|   |   `-- toto.py
|   `-- utils2
|   |-- __init__.py
|   `-- foo.py
`-- setup.py

So, in the "build" directory, I do not get all the the modules ("utils1"
and "utils2" directory), but only the first level of the package (files
under "utils" directory). Whereas all the files are included in the
utils-1.0.tar.gz archive made with "sdist".
How to modify setup.py and/or MANIFEST.in to include all the subdirectories
in the "build" directory when doing "setup.py build"? I have googled a bit
without finding anything.
These are my MANIFEST.in and setup.py files:

$ cat MANIFEST.in
include README
recursive-include utils *.py

$ cat setup.py
from distutils.core import setup

setup( name = 'utils'
, version = '1.0'
, url = ''
, author = ''
, author_email = ''
, packages = [ 'utils' ] )

Thanks in advance

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


setattr question

2009-02-19 Thread TP
Hi everybody,

I try to make a "link" (or shortcut, if you want) so that len(b_instance)
computes in fact len(a) (see the code below). I could write a method
__len__ to b, but I wonder if it is possible to make it with a
setattr/getattr trick, as I do below.

Thanks in advance,

Julien

##
class b( object ):

def __init__( self ):

super( b, self ).__init__()

a = [5,4,7]
b_instance = b()

setattr( b_instance, "__len__", getattr( a, "__len__") )
print len( a )
print id( a.__len__ )
print hasattr( b_instance, "__len__" )
print id( b.__len__ )
print len( b_instance )


I obtain:
$ p test_setattr.py
3
3083822540
True
Traceback (most recent call last):
  File "test_setattr.py", line 14, in 
print id( b.__len__ )
AttributeError: type object 'b' has no attribute '__len__'
Command failure: error 1 !


-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


super behavior

2009-01-25 Thread TP
Hi,

Hereafter is an example using super.
At the execution, we obtain:

coucou
init_coucou2
coucou1
coucou2
Traceback (most recent call last):
  File "essai_heritage.py", line 34, in 
print b.a
AttributeError: 'coucou' object has no attribute 'a'

Why Python does not enter in the __init__ method of coucou1?
If I replace the two lines using "super" by the two following lines, it
works perfectly:

coucou1.__init__( self )
coucou2.__init__( self )

##
class coucou1( object ):

def __init__( self
, a = 1 ):
self.a = a
print "init_coucou1"

def print_coucou1( self ):
print "coucou1"


class coucou2( object ):

def __init__( self
, b = 2 ):
self.b = b
print "init_coucou2"

def print_coucou2( self ):
print "coucou2"


class coucou( coucou1, coucou2 ):

def __init__( self ):

print "coucou"
super( coucou1, self ).__init__( )
super( coucou2, self ).__init__( )

b = coucou()
b.print_coucou1()
b.print_coucou2()
print b.a
print b.b
##
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: is this pythonic?

2009-01-22 Thread TP
Peter Otten wrote:

> If you can change the rest of your program to work smoothly with a
> dictionary I would suggest the following:
[snip]
>>> from collections import defaultdict
[snip]

Thanks a lot.
I didn't know defaultdict. It is powerful.

I begin to understand that people prefer using dictionaries than lists, so
as to take advantage of their automatic lookup feature.

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: is this pythonic?

2009-01-21 Thread TP
alex23 wrote:

> Try not to use 'dict' or the name of any of the other built-in types
> as labels.

Ops... Moreover I know it...

> You're stepping through an entire list just to pass another list to
> l.remove to step through and remove items from...in fact, given that
> list.remove deletes the -first- occurance of the item, you're asking
> it to loop through -again- to find the matching element which you've -
> already- detected. A better and cleaner approach would be to step
> through the list -once- and remove the item when you find it:
> 
> for index, record in enumerate(l):
> if record['title'] == 'ti':
> l.pop(index)

Ok, I will use this solution. But it is less pythonic than list
comprehensions.

> Or you could just use a list comprehension:
> 
> l = [d for d in l if d['title'] == 'ti']

Perhaps you mean rather:

l = [d for d in l if d['title'] != 'ti']
?

In fact, I cannot use this solution, because I want to get back the
dictionary with title 'ti', for another use (in fact, to add it to another
list, see below).

>> Precision: I have stored data in the list of dictionaries l, because in
>> my application I am sure that "title" is unique for each record. But
>> perhaps it is better to imagine that someday it will not be anymore the
>> case?
> 
> It's always better to design for what you know you need, not what you
> may possibly need in the future. You say that you are sure that record
> titles are unique, so why not use them as the dictionary keys, with
> the values as the values:
> 
>   records = {'ti': 1, 'to': 2}
> 
> This way your code can be replaced with:
> 
>   value = records.pop('ti') # if you want to know the value
>   del records['ti'] # if you just want to delete the entry
> 
> It's a lot simpler to work with and extend.

In fact, in my case, in cannot use this simple solution, because there are
other fields in each dictionary, not only 2. I was not clear in my post.
So my list is rather:
l=[{"title":"to", "color":"blue", "value":2}
{"title":"ti", "color":"red", "value":"coucou"}]

So, I will rather use your solution:

for index, record in enumerate(l):
if record['title'] == 'ti':
to_add_in_another_list = l.pop(index)
another_list.append(to_add_in_another_list )

> It's always better to design for what you know you need, not what you
> may possibly need in the future.

Ok. Do all the programmers agree with this principle?

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


is this pythonic?

2009-01-21 Thread TP
Hi,

Is the following code pythonic:

>>> l=[{"title":"to", "value":2},{"title":"ti","value":"coucou"}]
>>> dict = [ dict for dict in l if dict['title']=='ti']
>>> l.remove(*dict)
>>> l
[{'title': 'to', 'value': 2}]

Precision: I have stored data in the list of dictionaries l, because in my
application I am sure that "title" is unique for each record. But perhaps
it is better to imagine that someday it will not be anymore the case? And
rather use a data storage as the following?

l = { '001':{"title":"to", "value":2}, '002'
{"title":"ti","value":"coucou"}}

The problem with this storage is that it implies to manipulate some "ids"
that have not any meaning for a humain being (001, 002, etc).

Thanks a lot for you opinion,

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


exec in a nested function yields an error

2009-01-13 Thread TP
Hi everybody,

Try the following program:


def f():
def f_nested():
exec "a=2"
print a
f()


It yields an error.
$ python nested_exec.py
  File "nested_exec.py", line 3
exec "a=2"
SyntaxError: unqualified exec is not allowed in function 'f_nested' it is a
nested function

What is the problem?
Why?

Thanks

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


trying to modify locals() dictionary

2009-01-12 Thread TP
Hi everybody,

I try to modify locals() as an exercise.
According to the context (function or __main__), it works differently (see
below). Why? Thanks

Julien


def try_to_modify_locals( locals_ ):

locals_[ "a" ] = 2
print "locals_[ 'a' ]=", locals_[ "a" ]
return locals_

def test_modify_locals():

a = 3
l = try_to_modify_locals( locals() )
print l is locals()
print a

# Below, a remains equal to 3
print "test from test_modify_locals()"
test_modify_locals()

# But here, it works: a is modified
print "test from __main__"
a = 3
l = try_to_modify_locals( locals() )
print l is locals()
print a

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


change only the nth occurrence of a pattern in a string

2008-12-31 Thread TP
Hi everybody,

I would like to change only the nth occurence of a pattern in a string. The
problem with "replace" method of strings, and "re.sub" is that we can only
define the number of occurrences to change from the first one.

>>> v="coucou"
>>> v.replace("o","i",2)
'ciuciu'
>>> import re
>>> re.sub( "o", "i", v,2)
'ciuciu'
>>> re.sub( "o", "i", v,1)
'ciucou'

What is the best way to change only the nth occurence (occurrence number n)?

Why this default behavior? For the user, it would be easier to put re.sub or
replace in a loop to change the first n occurences.

Thanks

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


best way to do this

2008-12-02 Thread TP
Hi everybody,

>>> c=[(5,3), (6,8)]

>From c, I want to obtain a list with 5,3,6, and 8, in any order.
I do this:

>>> [i for (i,j) in c] + [ j for (i,j) in c]
[5, 6, 3, 8]

Is there a quicker way to do this?

Thanks

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to construct a list of only one tuple

2008-11-27 Thread TP
[EMAIL PROTECTED] wrote:

>> >>> a=("1","2")
>> >>> b=[("3","4"),("5","6")]
>> >>> list(a)+b
>> ['1', '2', ('3', '4'), ('5', '6')]
> 
 a = ("1", "2")
 b = [("3", "4"), ("5", "6")]
 [a] + b
> [('1', '2'), ('3', '4'), ('5', '6')]

Thanks a lot.
Why this difference of behavior between list(a) and [a]?

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


how to construct a list of only one tuple

2008-11-27 Thread TP
Hi,

If I do:

>>> a=("1","2")
>>> b=[("3","4"),("5","6")]
>>> list(a)+b
['1', '2', ('3', '4'), ('5', '6')]

I would like rather to obtain:

[('1', '2'), ('3', '4'), ('5', '6')]

Am I compelled to do:

>>> c=[]
>>> c.append(a)
>>> c+b
[('1', '2'), ('3', '4'), ('5', '6')]

Thanks

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


how to document a property

2008-11-27 Thread TP
Hi everybody,

I know how to document a function or a method, with a docstring (see below
for "foo" method documentation ("bar")).
But, how to document a property (below, self.d)?

###
class a():
   def __init__( self ):
  self.d = 2
   def foo( self ):
  "bar"

b=a()
print dir(b)
methods = [ el for el in dir( b ) ]
for meth in methods:
   if hasattr( getattr( b, meth ), "__doc__" ):
  print meth, " :\n", getattr( b, meth ).__doc__
###

When I execute this script, I obtain for self.d:

###
[...]
__module__  :
str(object) -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.

d  :
int(x[, base]) -> integer

Convert a string or number to an integer, if possible.  A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!)  When converting a string, use
the optional base.  It is an error to supply a base when converting a
non-string. If the argument is outside the integer range a long object
will be returned instead.
[...]
###

What is this default documentation?
Why?

Thanks

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


import in a class

2008-11-26 Thread TP
Hi everybody,

Here is a file "test_import_scope.py":
##
class a():
   import re
   def __init__( self ):
  if re.search( "to", "toto" ):
 self.se = "ok!"
   def print_se( self ):
  print self.se
a().print_se()
##

When python executes this file, we obtain an error:

$ python test_import_scope.py
[...]
NameError: global name 're' is not defined

Why?

When the re module is imported in the __init__ function or out of the class
(at the top of the file), it works obviously perfectly.

Thanks in advance,

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


multiple breaks

2008-11-13 Thread TP
Hi everybody,

Several means to escape a nested loop are given here:

http://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python

According to this page, the best way is to modify the loop by affecting the
variables that are tested in the loops. Otherwise, use exception:

"If, for some reason, the terminating conditions can't be worked out,
exceptions are a fall-back plan."

In the following example, is this possible to affect the two iterators to
escape the two loops once one "j" has been printed:

for i in range(5):
for j in range(i):
   print j
   # I would type "break 2" in shell bash
   # In C, I would set j=i-1 and i=4
   # In Python, is this possible to affect the two iterators?

Or the only means is to use exception?

Thanks in advance

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


script that parses command line, and execfile('')

2008-11-03 Thread TP
Hello,

I have a script that uses the "optparse" package to parse the command line.
For example:

$ script.py --help
# displays help about script.py

Is this possible to call such a script with execfile('') once in the Python
interactive shell?

>>> execfile( 'script.py' )

I get errors because there is no argv dictionary when used with execfile.

How to solve this problem, so that I am able to use script.py in command
line as well as with execfile?

Thanks

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


redirection in a file with os.system

2008-11-03 Thread TP
Hi everybody,

The following code does not redirect the output of os.system("ls") in a
file:

import sys, os
saveout = sys.stdout
fd = open( 'toto', 'w' )
sys.stdout = fd
os.system( "ls" )
sys.stdout = saveout
fd.close()

Whereas the following works:

old_stdout = os.dup( sys.stdout.fileno() )
fd = os.open( 'bar', os.O_CREAT | os.O_WRONLY )
os.dup2( fd, sys.stdout.fileno() )
os.system( "ls" )
os.close( fd )
os.dup2( old_stdout, sys.stdout.fileno() )

Why?

I have another question: with this last code using os.open, the problem is
that the file 'bar' is not removed before being written. So, it could lead
to errors: the file 'bar' is overwritten, but extra lines from previous
executions could remain.
Am I compelled to use os.unlink (or os.remove) before calling
os.system("ls")?

Thanks

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


length of a tuple or a list containing only one element

2008-11-03 Thread TP
Hi everybody,

I have a question about the difference of behavior of "len" when applied on
tuples or on lists. I mean:

$ len( ( 'foo', 'bar' ) )
2
$ len( ( 'foo' ) )
3
$ len( [ 'foo', 'bar' ] )
2
$ len( [ 'foo' ] )
1

Why this behavior for the length computation of a tuple?
For my application, I prefer the behavior of length for a list. If I want to
store some values in a tuple because they should not be modified, the case
where the tuple contains only one element bothers me.

Thanks

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: question about the textwrap module

2008-10-28 Thread TP
Gabriel Genellina wrote:

> You may pre-process your text (stripping redundant whitespace) before
> using textwrap:

Thanks Gabriel for your answers!
I finally have subclassed textwrap.TextWrapper.

Julien


-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


question about the textwrap module

2008-10-27 Thread TP
Hi everybody,

Recently, I have tried to improve the look of the printed text in command
line. For this, I was compelled to remove redundant spaces in strings,
because in my scripts, often the strings are spreading on several lines.

For example, "aaa   bbb" had to be transformed in "aaa bbb".
I have coded some simple functions to do that.

Today, by examining Python documentation, I have found an interesting
module:

http://www.python.org/doc/2.5.2/lib/module-textwrap.html

But, I haven't found any way to do my redundant space deletion with this
module? Am I right?

Thanks

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


redirection of standard output of a Python command to a Python variable

2008-10-27 Thread TP
Hi everybody,

I try to find a quick way to redirect the standard output of a Python
command (for example: print "message") to a python variable "foobar".
Ok, in this simple example, I could do foobar = "message", but in
fact 'print "message"' could be replaced by any Python function writing on
standard output.
I have googled on this subject.
To redirect to a variable, I could use a temporary file:

import sys
saveout = sys.stdout
fsock = open('out.log', 'w')
sys.stdout = fsock
print 'message'
sys.stdout = saveout
fsock.close()
fsock = open('out.log', 'r')
foobar = fsock.read()
fsock.close()
print "foobar= ", foobar

To redirect a system standard output directly to a variable (without
temporary file), I could do:

import os
f = os.popen("ls")
print f.read()
f.close()

But, how can I get the standard output of a Python command (print "message")
directly into a variable?

Thanks

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


execute a function before and after any method of a parent class

2008-10-03 Thread TP
Hi everybody,

I would like to be able to specialize an existing class A, so as to obtain a
class B(A), with all methods of B being the methods of A preceded by a
special method of B called _before_any_method_of_A( self ), and followed by
a special method of B called _after_any_method_of_A( self ).

The goal is to avoid to redefine explicitly in B all methods of A.

Is this possible in Python?

Thanks a lot

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


raw_input on several lines

2008-08-02 Thread TP
Hi everybody,

When using raw_input(), the input of the user ends when he types Return on
his keyboard.
How can I change this behavior, so that another action is needed to stop the
input? For example, CTRL-G. It would allow the user to input several lines.

Thanks

Julien


-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


how to avoid line return when using python -c 'print "foo"'

2008-07-18 Thread TP
Hi everybody,

All my problem is in the title.
If I try:

$ python -c 'print "foo",'

It does not change anything, surely because the line return is added
by "python -c".

Thanks in advance

Julien

-- 
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
--
http://mail.python.org/mailman/listinfo/python-list


Re: interpretation of special characters in Python

2008-07-07 Thread TP
Peter Pearson wrote:

> I don't understand exactly what you mean by "Sorry"

I means: please forgive me for having said that it does not work with
variables, because it is completely false.

Thanks one more time

Julien

-- 
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
--
http://mail.python.org/mailman/listinfo/python-list


Re: interpretation of special characters in Python

2008-07-07 Thread TP
Peter Otten wrote:

>>>> esc = os.environ["esc"].decode("string-escape")
>>>> esc
> '\x1b'
>>>> print "%s[30;44malles so schoen bunt hier%s[0m" % (esc, esc)
> alles so schoen bunt hier

Thanks a lot for your help. It works perfectly.
Indeed, one can read in the documentation concerning encodings:

"Produce a string that is suitable as string literal in Python source code"

-- 
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
--
http://mail.python.org/mailman/listinfo/python-list


Re: interpretation of special characters in Python

2008-07-07 Thread TP
TP wrote:

> So, the python print command *can* interpret these 4-character as a single
> character. It would be odd if there were no possibility to do the same
> thing when the characters are (i) stored in a python variable

Sorry, it works when using variables. Try for example:

col="[0;31m"
esc="\033"
colreset="[0m"
print esc + col + "foobar" + esc + colreset

-- 
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
--
http://mail.python.org/mailman/listinfo/python-list


Re: interpretation of special characters in Python

2008-07-06 Thread TP
Peter Pearson wrote:

Thanks for your answer.

> When you run echo, it recognizes the 4-character "esc" as a
> convention for representing a single character, and performs
> the re-interpretation for you.  When you tell python
> "print '\033[30;44m foo \033[0m'", python interprets
> the "\033" as a single character.

So, the python print command *can* interpret these 4-character as a single
character. It would be odd if there were no possibility to do the same
thing when the characters are (i) stored in a python variable, or (ii) come
from the environment variables. Does anybody know any way to re-interpret a
string in Python? I have tried to play with "eval" (as in bash), but it
does not yield anything.

-- 
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
--
http://mail.python.org/mailman/listinfo/python-list


Re: interpretation of special characters in Python

2008-07-06 Thread TP
Dennis Lee Bieber wrote:

> Off-hand, I'd probably try first with:
> 
> csi = "\033["
> 
> and then define your
> 
> colorblackondarkblue = $csi"30;44m"

Thanks for your answer.
I have tried this slight modification, but it does not change anything on my
terminal.


-- 
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
--
http://mail.python.org/mailman/listinfo/python-list


interpretation of special characters in Python

2008-07-06 Thread TP
Hi everybody,

I am new to Python, I try to understand how Python treats special
characters. For example, if I execute the following line in a shell
console, I obtain a colored string:

$ python -c "print '\033[30;44m foo \033[0m'"

So, it works.
Some time ago, I have made a lot of shell variables with all possible colors
(with shell functions executed each time I launch a new shell). For
example:

$ echo -e $esc$ColorBlackOnDarkblue foo $esc$ColorReset

gives the same result than the python command above.
To know the corresponding non-interpreted characters, I can use the -n
option of echo:

$ echo -n $esc$ColorBlackOnDarkblue foo $esc$ColorReset
\033[30;44m foo \033[0m

So, it is exactly the string above, as expected.

My problem arises when it comes to get these shell variables ( $esc,
$ColorBlackOnDarkblue, $ColorReset) in a Python script, with os.environ, in
the following 5-line script:

import os
Color = os.environ['ColorBlackOnDarkblue']
ColorReset = os.environ['ColorReset']
Esc = os.environ['esc']
print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset)

Run this script color.py, but after having defined these shell variables in
a shell:

$ export esc="\033"
$ export ColorBlackOnDarkblue="[30;44m"
$ export ColorReset="[0m"

When I execute the Python script, I do not obtain any special character
interpretation in Python:

$ python color.py
\033[30;44m foo \033[0m

Why? What is the problem? Is there any solution?
I really want to get my shell color variables.

Thanks a lot

-- 
TP (Tribulations Parallèles)

"Allez, Monsieur, allez, et la foi vous viendra." (D'Alembert).
--
http://mail.python.org/mailman/listinfo/python-list