Re: Feature request: String-inferred names

2009-11-28 Thread Lie Ryan

On 11/28/2009 3:08 PM, The Music Guy wrote:

As for your code, I haven't seen it, so it would be hard for me to say
exactly how the new syntax would come into play. What I can tell you,
however, is that the parts of your code that would use it would
probably be easier to read and change to anyone with a firm grasp of
the proposed syntax.


Isn't this much easier to read and grasp?

obj.d["my_%s" % foo] += 3

doesn't need new syntax as well.


Even if this sort of thing only needed to happen a few times in an
entire project, the project as a whole could only benefit from it. My
projects rely on a lot of metaclassing for the automatic generation of
properties and methods, which saves tremendous amounts of coding.


If you use it a lot, it is likely 1) you have abused class syntax for 
what should have been a dict or 2) what you need is to override 
__getattr__/__getattribute__ and __setattr__

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


Re: need clarification on -0

2009-11-28 Thread Steven D'Aprano
On Fri, 27 Nov 2009 23:09:06 -0800, moijes12 wrote:

> Hi
> 
> I know the value -0 is quite meaningless and makes little sense.

Actually, when it comes to floating point values, it is very useful to be 
able to distinguish between -0 and +0.


> But I
> was just fiddling.I am unable to figure out the below result
> 
> 
 -0 and True
> 0 --> (Why is this 0 and not say True or False)

You need to know two things about Python:

(1) All values can be interpreted in a boolean context:

if None:
print "this will never be printed"
else:
print "this is always printed"

False values include: None, 0, 0.0, "", [], {} and of course False.

True values include nearly everything else.


(2) `and` and `or` are short-cut operators. They return the first 
argument which unambiguously defines the result:

X and Y => X if X is a false value, and Y if X is a true value.
X or Y => X if X is a true value, and Y if X is a false value.


Why do `and` and `or` return objects other than True and False? This is 
especially useful when using `or` in situations like this:

process(main_list or fallback_list)

which will process the first list of the two which is not empty.


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


Re: Feature request: String-inferred names

2009-11-28 Thread Steven D'Aprano
On Fri, 27 Nov 2009 20:02:31 -0800, The Music Guy wrote:

> That PEP seems to pretty clearly state that it applies only to the 3.x
> branch and not to the 2.x branch. Is there maybe a slim chance of
> getting my idea added to 2.7, or even 2.8? :D


The only new features being added to 2.7 are features which are also 
being added to 3.x. There is no chance at all of having new features 
added to 2.7 which isn't added to 3, unless that feature is specifically 
to make it easier to migrate from 2 to 3.



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


Re: Some Basic questions on the use of CTRL and ALT Keys

2009-11-28 Thread Lie Ryan

On 11/28/2009 6:20 PM, joy99 wrote:

I was writing a transliteration program from Bengali to English and
vice versa. The program using Unicode chart is giving me perfect
outputs in Bengali and vice versa with Bengali input ->  English.
I wanted to add some more power to the key board entry scheme, as I
have developed few fonts also and now trying to work out a windows
based word processor in Bengali.
Thank you for your kind answer.
It helped me lot.
ALT portion I'll work out on my own.
Sorry for a wrongly given problem statement.
Wishing you a happy day ahead,
Regards,
Subhabrata.


If I haven't misunderstood you, you want to capture keyboard input 
involving the CTRL and ALT key, am I correct?


Getting keyboard input with modifier keys depends on your GUI widgets. 
Which are you using? Tkinter? wxWidget? PyQT? or plain ol' terminal?

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


Re: python logging filters

2009-11-28 Thread Vinay Sajip
On Nov 27, 1:11 pm, Grimsqueaker  wrote:
> When I add a Filter to a Handler, everything works as expected (ie.
> all messages sent from Loggers below the Filter's level are allowed
> through), but when I add the Filter directly on to the Logger, only
> that Logger is blocked, regardless of the contents of the Filter.

The key thing to remember is that when a logger processes an event,
handlers attached to it *and all its parents* are offered the event
for handling. In the case where you have just one handler and it has
the filter attached, filtering works as you expected. By attaching the
filter to the root logger, you are not filtering its handler; this
handler is invoked for events logged to all the other loggers, and so
(apart from the event at the root logger) those events are not
filtered.

For some examples of filter usage, see this post:

http://groups.google.com/group/comp.lang.python/msg/2eb4cf8f879c6451

Regards,

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


Re: python bijection

2009-11-28 Thread Joshua Bronson
On Nov 27, 9:36 pm, "Gabriel Genellina" 
wrote:
> En Fri, 27 Nov 2009 15:12:36 -0300, Francis Carr   
> escribió:
>
> > I was really inspired by this discussion thread! :-)
>
> > After much tinkering, I think I have a simpler solution.  Just make
> > the inverse mapping accessible via an attribute, -AND- bind the
> > inverse of -THAT- mapping back to the original.  The result is a
> > python dict with NO NEW METHODS except this inverse-mapping
> > attribute.  I have posted it on code.activestate.com as  > href="http://code.activestate.com/recipes/576968/";>Recipe 576968:
> > Flipdict -- python dict that also maintains a one-to-one inverse
> > mapping
>
> Nice idea!

Indeed! Thanks for sharing! I liked this so much I added something
similar in http://bitbucket.org/jab/toys/src/tip/bidict.py (I made the
inverse available via a .inv property, as well as via the unary ~
operator (by analogy to bitwise inverse)). I also got rid of getinv,
popinv, et al. to keep the API leaner as you recommend. I've kept the
slice syntax though as well as namedbidect, so for now I guess I'm
allowing for many ways to skin this cat.

> Just a couple of comments:
>
> Instead of:
>         self._flip = dict.__new__(self.__class__)
> I'd write:
>         self._flip = self.__class__()
> unless I'm missing something (but see the next point).

How would this not cause infinite recursion?

> Also, although Python's GC is able to handle them, I prefer to avoid  
> circular references like those between x and x._flip.  Making self._flip a  
> weak reference (and dereferencing it in the property) should be enough.

If both self._flip and self._flip._flip are weak references, no strong
references to the inverse mapping survive leaving the constructor
scope. Unless I'm missing something, only one of these can be a weak
reference, and then you'd have to do something like this in the
property to prevent "TypeError: FlipDict is not callable":

@property
def flip(self):
try:
# we're an inverse, self._flip is a weak reference
return self._flip()
except TypeError:
# we're a forward mapping, self._flip is a strong
reference
return self._flip
-- 
http://mail.python.org/mailman/listinfo/python-list


dvb3

2009-11-28 Thread luca72
hello i try to use the python-dvb3 bindings, but i have some problem:
fe = dvb3.frontend.Frontend(0)
type = tipo_1 = fe.get_dvbtype()
now i need to set the parameters
parametri = dvb3.frontend.QPSKParameters(frequency=frequency,
inversion=2 , symbol_rate=27500,  fec_inner=9)
but when i use
fe.set_frontend(parametri)
i get the error
The debugged program raised the exception IOError
"(22, 'Invalid argument')"
File: frontend.pyx, Line: 364

thedef is as follow :
 def set_frontend(self, parameters):
global cfrontend
cdef cfrontend.dvb_frontend_parameters p
if pack_parameters(&p, parameters) == 0:
raise ParameterError, "Incorrect parameter type"
if ioctl(self.fd, cfrontend.FE_SET_FRONTEND, &p) == -1:
raise_ioerror()

can you hel me

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


Python MySQL: clean multiple foreign keys table

2009-11-28 Thread Threader Slash
Hi Everybody,

I am working with Python MySQL, and need to clean a table in my database
that has 13328 rows.

I can not make a simple drop table, because this table is child and also
father of other child foreign-keys linked on it. If I try drop table, the
system forbidden me. The table is defined with ON UPDATE CASCADE, ON DELETE
CASCADE and InnoDB; The primary_key index to that table is defined as

productID INT(6) NOT NULL AUTO_INCREMENT ...
PRIMARY KEY (productID,productNO)

Therefore, I just have to clean; this will automatically restore the table
primary key index to 1 for the next input. Right?

This procedure worked fine for another table that was a father table, but
not also a father and child table. But, for this table, which is child and
father of other tables, I got stuck on it.

Here is the code - productID is my primary index key to this table:


def clean_tableProduct(self):
getMaxID_MySQLQuery = """SELECT MAX(productID)
FROM product;"""

cleanTabeMySQLQuery="""DELETE FROM product WHERE productID
<=%s;"""

self.cursorMySQL.execute(getMaxID_MySQLQuery)

for row in self.cursorMySQL:
self.cursorMySQL.execute(cleanTabeMySQLQuery,(row[0],))

If I go to the MySQL console to check the processing results, it gets me:

mysql> SELECT MIN(productID)
FROM product;
4615748

mysql> SELECT MAX(productID)
FROM product;
4629075

If I run the same command on console to clean the table, it works:

mysql> DELETE FROM product WHERE productID <='4629075';
Query OK, 13328 rows affected (0.64 sec)


and shows me what I would normally expect.

However, if I go to Python function after having cleaned the table on
console, and run the program again, and clean the table to restart the
processing, it restarts the table index not with MIN:1, but instead 4629076.

Any suggestion?

All comments and suggestions are highly appreciated and welcome.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some Basic questions on the use of CTRL and ALT Keys

2009-11-28 Thread joy99
On Nov 28, 2:22 pm, Lie Ryan  wrote:
> On 11/28/2009 6:20 PM, joy99 wrote:
>
> > I was writing a transliteration program from Bengali to English and
> > vice versa. The program using Unicode chart is giving me perfect
> > outputs in Bengali and vice versa with Bengali input ->  English.
> > I wanted to add some more power to the key board entry scheme, as I
> > have developed few fonts also and now trying to work out a windows
> > based word processor in Bengali.
> > Thank you for your kind answer.
> > It helped me lot.
> > ALT portion I'll work out on my own.
> > Sorry for a wrongly given problem statement.
> > Wishing you a happy day ahead,
> > Regards,
> > Subhabrata.
>
> If I haven't misunderstood you, you want to capture keyboard input
> involving the CTRL and ALT key, am I correct?
>
> Getting keyboard input with modifier keys depends on your GUI widgets.
> Which are you using? Tkinter? wxWidget? PyQT? or plain ol' terminal?

You are very right. I am using IDLE on WinXP and for building GUI-
TKinter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Intro To Python Using Turtle Graphics

2009-11-28 Thread Terry Reedy

Enkidu wrote:

Ben Finney wrote:


Oh, so trash-talking in *other* forums where you feel safe from being
caught is okay? ;-)


I take your point, but the other group in question is a 'local' group.


I think he intended to mean that it was a local group where 
trash-talking and stupid comments are the norm.


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


Re: Python & OpenOffice Spreadsheets

2009-11-28 Thread Paul Rudin
r  writes:

> On Nov 23, 4:49 am, Gerhard Häring  wrote:
>> Is there a *simple* way to read OpenOffice spreadsheets?
>>
>> Bonus: write them, too?
>>
>> I mean something like:
>>
>> doc.cells[0][0] = "foo"
>> doc.save("xyz.ods")
>>
>> >From a quick look, pyodf offers little more than just using a XML parser
>
>
> I find the syntax far to complicated than it should be. Here is an
> example just to insert some text..

[employing weapons of mass snippage]

It's true that it's a hassle, but the boiler plate stuff can be stuck in
a function and then forgotton about really.


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


Re: Intro To Python Using Turtle Graphics

2009-11-28 Thread Ben Finney
Terry Reedy  writes:

> Enkidu wrote:
> > Ben Finney wrote:
> >> Oh, so trash-talking in *other* forums where you feel safe from
> >> being caught is okay? ;-)
> >>
> > I take your point, but the other group in question is a 'local'
> > group.
>
> I think he intended to mean that it was a local group where
> trash-talking and stupid comments are the norm.

Well no, I'm not passing any comment on the group. Merely that
trash-talk isn't made any more acceptable just because the target of the
trash-talk isn't present to hear it.

But more importantly, my comment was intended as a pleasant jibe (hence
the smiley), not a severe admonishment.

-- 
 \ “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\Brain, but if we give peas a chance, won't the lima beans feel |
_o__)left out?” —_Pinky and The Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature request: String-inferred names

2009-11-28 Thread The Music Guy
On Nov 28, 3:07 am, Lie Ryan  wrote:
> On 11/28/2009 3:08 PM, The Music Guy wrote:
>
> > As for your code, I haven't seen it, so it would be hard for me to say
> > exactly how the new syntax would come into play. What I can tell you,
> > however, is that the parts of your code that would use it would
> > probably be easier to read and change to anyone with a firm grasp of
> > the proposed syntax.
>
> Isn't this much easier to read and grasp?
>
> obj.d["my_%s" % foo] += 3
>
> doesn't need new syntax as well.

Actually, that's similar to my backup solution, which is a variant of
the "attrs" class that PEP 363 provides. It does make things easier to
read, but a new syntax would still be better because:

1.) A new syntax would apply to _everything_ as it would be a hook to
the very mechanism that gets the value of a member from an object and
does not rely on an object defining the magic "d" property. I suppose
you could argue that an enhancement could be made to the language that
says that all objects must define the magic "d" (so the builins
"object" and "type" would have to define it). That also has the added
benefit of not conflicting with PEP 3003, which says it is fine to add
new methods (and I would assume properties as well) to existing
classes.

2.) Ben's patch for his proposed syntax generated an aproximate 1%
performance hit for the interpreter overall versus a >40% increase
where code that used the getattr/settattr functions was modified to
use the proposed syntax. The magic "d" MIGHT have a performance
increase over the getattr/setattr functions, but a syntax would still
be significantly faster because there would be less function
dereferencing/calling. For the purposes that I had intended for the
syntax to be used, that would definitely matter.

> If you use it a lot, it is likely 1) you have abused class syntax for
> what should have been a dict or 2) what you need is to override
> __getattr__/__getattribute__ and __setattr__

Oh boy...here we go. :|

Please listen. In all the time I've spent in the coding community
(that's at least 7 years) and especially since I started paying
attention to the Python community (2 years), I have noticed a trend:
When one coder does something that another cannot understand,
frequently the other will assume the former is not only doing things
wrong, but is doing them _blatantly_ wrong. I have caught myself
making that very assumption many times in the past, and I've tried
hard to build up an immunity against the impulse to make that
assumption. At this point, I don't even believe in such a thing as a
universal "wrong way" and a "right way" to code that applies to every
circumstance. The way to solve a problem depends on the problem. When
it comes to coding, there is not an absolute "right" way or "wrong"
way--unless we're talking about, say, stealing closed source code
without permission, or deliberately coding in a way that will cause
problems for the end user (like causing memory clogs or buffer
overflows and whatnot).

All of this can be determined through common sense. And yet I continue
to see the attitude of "my solution is the ONLY solution to your
problem, and it doesn't matter if I don't even actually understand the
problem." Not everyone does this, but it is a frequent enough
occurence to be worth noting. If I had to pull a number out of my
magic bag, I would say 4 out of 10 resposes have at least a hint of
this attitude, and  2.5/10 where it is very obvious.

But I digress. I've already gone over other possible solutions and the
one I am using seems to fit the bill better than any other yet
presented to me, including the ones you just suggested. In fact, I'm
fairly certain that __getattr__ and friends even apply to the
situation, or if they do, they're certainly inferior alternatives to
the use of getattr/setattr. Not that I'm calling you inferior--I'm
just saying that if you had a better understanding of the problem you
would not see __getatrr__ et al. as parts of a possible solution
because they don't really make logical sense given the circumstances.

...and I have one last thing to say. I feel very strongly that
metaclassing is a fiercely underestimated and largely untapped source
of good coding solutions. I hope that many coders will see this and
help to make it more adoptable by the masses; at present it is seen as
a big, scary beast that is hard to tame and even harder to drive. It
is portrayed as something dangerous that should only be used in
relatively rare situations. I disagree with this view. It is the view
itself which makes it seem so dangerous (in other words, it is self-
perpetuating).

Well, that's about enough yakking for 5:30 in the morning...time to
give my noggin a rest.

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


Re: Feature request: String-inferred names

2009-11-28 Thread Ben Finney
The Music Guy  writes:

> Please listen. In all the time I've spent in the coding community
> (that's at least 7 years) and especially since I started paying
> attention to the Python community (2 years), I have noticed a trend:
> When one coder does something that another cannot understand,
> frequently the other will assume the former is not only doing things
> wrong, but is doing them _blatantly_ wrong.

I think you may be misinterpreting the message.

> At this point, I don't even believe in such a thing as a universal
> "wrong way" and a "right way" to code that applies to every
> circumstance. The way to solve a problem depends on the problem.

You'll find firm agreement on that in this group.

> When it comes to coding, there is not an absolute "right" way or
> "wrong" way--unless we're talking about, say, stealing closed source
> code without permission, or deliberately coding in a way that will
> cause problems for the end user (like causing memory clogs or buffer
> overflows and whatnot).

However, when it comes to a *specific*, mature programming language,
there *are* right and wrong ways. Or, at least, there are ways
encouraged or discouraged by the language, its interfaces, its style
guides, and its community.

Which is very important: it's the rare program that is only ever read by
one person in one context. Far more often, the same program needs to be
read multiple times, by multiple people, in multiple contexts, over
multiple iterations of maintenance. And for that to be feasible, it's
very important to write the program the right way *for that language*.

Sticking to local conventions has a great deal of practical merit in the
medium of human-to-human communication that we call “programming”.
Progress depends on doing things differently; but maintainability
depends on keeping unexpected differences to a minimum.

-- 
 \ “The truth is the most valuable thing we have. Let us economize |
  `\ it.” —Mark Twain, _Following the Equator_ |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature request: String-inferred names

2009-11-28 Thread Lie Ryan

On 11/28/2009 10:38 PM, The Music Guy wrote:

If you use it a lot, it is likely 1) you have abused class syntax for
what should have been a dict or 2) what you need is to override
__getattr__/__getattribute__ and __setattr__


Oh boy...here we go. :|



ok, then what's your use case, AFAICT in the discussion here and 
previous ones, nobody has yet described a realistic and compelling 
situation where setattr/getattr is the best solution. That's why the 
discussion tended to end with "not used frequently enough"; simply 
because nobody can turn up with a use case to justify a new syntax, 
especially since all the proposed syntax are ugly (the most acceptable 
one, for me, is obj.[foo], still ugly but not as ugly as the others).

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


Re: a 100-line indentation-based preprocessor for HTML

2009-11-28 Thread Colin W.

On 27-Nov-09 22:04 PM, Steve Howell wrote:

Python has this really neat idea called indentation-based syntax, and
there are folks that have caught on to this idea in the HTML
community.

AFAIK the most popular indentation-based solution for generating HTML
is a tool called HAML, which actually is written in Ruby.

I have been poking around with the HAML concepts in Python, with the
specific goal of integrating with Django.   But before releasing that,
I thought it would be useful to post code that distills the basic
concept with no assumptions about your target renderer.  I hope it
also serves as a good example of what you can do in exactly 100 lines
of Python code.

Here is what it does...

 You can use indentation syntax for HTML tags like table.

 From this...

 table
 tr
 td
 Left
 td
 Center
 td
 Right

 ...you get this:
 ...


[snip]

This is a neat idea but would a two character indentation not be enough?

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


Re: debugger on system with Python 2 and 3

2009-11-28 Thread Detlev Offenbach
Hi,

eric4 snapshot releases support Python3.

Detlev

Yo Sato wrote:

> Hi,
> 
> I am a relative newcomer to the Python language, and only write Python
> 3. Now I would very much like to a more-than-basic debugger. However
> it seems as if the fact that I have both Python 2 and 3 on the system
> complicates the matter...
> 
> First I tried to use something called pydb, but it seems to invoke
> python 2, and I don't know quite how to (or whether I can) configure
> it for Python 3.
> 
> Secondly I installed something called IDLE3, which complains that TK
> is not configured for Python 3.
> 
> I don't want to remove or default to Python 2, as there seem to be a
> number of programs that rely on it.
> 
> I wonder how best to avoid my problems. Would perhaps somebody in the
> same sort of situation share their wisdom??
> 
> Yo

-- 
Detlev Offenbach
[email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some Basic questions on the use of CTRL and ALT Keys

2009-11-28 Thread Vlastimil Brom
2009/11/28 joy99 :
> On Nov 28, 2:22 pm, Lie Ryan  wrote:
>> On 11/28/2009 6:20 PM, joy99 wrote:
>>
>> > I was writing a transliteration program from Bengali to English and
>> > vice versa. The program using Unicode chart is giving me perfect
>> > outputs in Bengali and vice versa with Bengali input ->  English.
>> > I wanted to add some more power to the key board entry scheme, as I
>> > have developed few fonts also and now trying to work out a windows
>> > based word processor in Bengali.
>> > Thank you for your kind answer.
>> > It helped me lot.
>> > ALT portion I'll work out on my own.
>> > Sorry for a wrongly given problem statement.
>> > Wishing you a happy day ahead,
>> > Regards,
>> > Subhabrata.
>>
>> If I haven't misunderstood you, you want to capture keyboard input
>> involving the CTRL and ALT key, am I correct?
>>
>> Getting keyboard input with modifier keys depends on your GUI widgets.
>> Which are you using? Tkinter? wxWidget? PyQT? or plain ol' terminal?
>
> You are very right. I am using IDLE on WinXP and for building GUI-
> TKinter.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
You may check e.g.:
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

hth,
 vbr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: pdfrw pure-Python PDF file reading and writing

2009-11-28 Thread Patrick Maupin
On Nov 27, 2:35 am, Patrick Maupin  wrote:
> pdfrw is a basic PDF file manipulation library, developed and tested
> on Python 2.5 and 2.6.
>
> pdfrw can read and write PDF files, and can also be used to read in
> PDFs which can then be used inside reportlab (as source material for
> new PDFs).  This is also the underlying library for a new rst2pdf
> extension (not yet released, but in rst2pdf subversion) which allows
> arbitrary fragments of source PDFs to be embedded in the output PDF
> (without rasterization).
>
> No releases yet (and none immediately planned), but the interface is
> reasonably stable, it seems to work pretty well, and you can download
> the code and a few working examples at pdfrw.googlecode.com
>
> Feedback and/or code contributors always welcome!
>
> Best regards,
> Patrick Maupin

Apparently forgot URL when I was sleep-typing last night:
pypdf.googlecode.com

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


Re: python bijection

2009-11-28 Thread Patrick Maupin
On Nov 19, 8:36 pm, Ben Finney  wrote:
> Carl Banks  writes:
> > On Nov 19, 3:24 pm, Joshua Bronson  wrote:
> > Apart from the GPL, it seems perfectly fine to release, and looks like
> > an interesting strategy. I've wanted one of those once in a while,
> > never enough to bother looking for one or writing one myself.
>
> I would think GPL is an excellent choice for such a library then, if the
> author's intention is to encourage more software to be free software so
> that it can incorporate a unique library like this.

Well, yes and no.

This bidict class sounds nice and full-featured, especially after the
changes prompted by the fruitful discussion.  I personally use inverse
mappings on a regular basis, but for the most part, my data doesn't
change all that dynamically (or performance doesn't really matter), so
when I need to go backwards I often do something like:

inverse_mapping = dict((y, x) for (x, y) in forward_mapping.iteritems
())

Having said that, if I ever actually *need* something more full-
featured to add to non-GPLed software, I'd just write it (and release
it under a permissive license).  IMHO, GPLing something this simple is
really the tail trying to wag the dog.

Case in point:  I was just using rst2pdf to combine some restructured
text and SVG images, using svglib.  svglib had some bugs and didn't
work right on my PDFs.  svglib is not developed publicly, and the
author is somewhat slow to accept patches.  Since svglib is reasonably
small, if it had been released under a permissive license, or even the
LGPL, I probably would have just copied it into the rst2pdf repository
and fixed it.  If it were any smaller, I would have rewritten it.  I
don't own the rst2pdf package, and didn't really want a license
discussion about 1K of source lines dictating a license change on 15K
lines.  As it is, I figure the svglib author will probably get around
to fixing the bug at some point anyway, and for now I can easily use
PDFs for my graphics input format, so I cleaned up and added to some
old PDF code I had lying around, and released it as the open source
pdfrw package, and now rst2pdf can use that to import PDFs as vector
images without rasterizing them -- a new capability.  So in this case,
the GPL spurred open-source development, in exactly the same way that
proprietary licenses do...

I'm quite happy to *use* GPLed software (and greatly appreciate the
authors' efforts), and I'm even sometimes willing to debug or add
features and submit patches to GPLed software, and I might even have a
(business, not political) reason to release some software under the
GPL myself someday.  But if I ever did release something under the GPL
for business reasons, it would be because I also had the right to also
offer a proprietary version.  This would require that I owned _all_
the code in the package, so the implication is:  I'm not going to use
your tiny little GPLed code in any major software I write for release,
whether my software is GPLed or not.

The LGPL is different.  I view the LGPL as a statement of "if you ever
add related functionality to this or fix a bug in this in a shipping
product, I'd like to see the fix, please" and I could even see myself
releasing something with this license under the right circumstances.

Now if I were doing a web service, it would be a different story.  I
would be quite happy to add your GPLed software into the mix, so if
that's a terrible thing, perhaps you should consider affero for your
future offerings :-)

Best regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


filename of calling function?

2009-11-28 Thread Phlip
Consider these two python modules:

aa.py

def a():
print '?'

bb.py
  import aa

def bb():
  aa.a()

bb()

How do I make the print line emit the filename of bb.py? (It could be
anything.)

I am currently playing with sys.exc_info, but it seems to only emit
the stack between the raise and the except. Could be pilot error, of
course. Thanks for any help!

--
  Phlip
  http://c2.com/cgi/wiki?ZeekLand
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a 100-line indentation-based preprocessor for HTML

2009-11-28 Thread Martijn Arts
It´s quite clear to me: Not. I've taken a look at the "Timebar", and in the
last
two months there has been no change at all.

On Sat, Nov 28, 2009 at 7:32 AM, Steve Howell  wrote:

> On Nov 27, 9:56 pm, "David Williams"  wrote:
> > You might want to take a look at this:
> >
> > http://www.ghrml.org/
> >
>
> Yep, it's not clear how actively they are maintaining that.  The fact
> that it seems to target Genshi only might be limiting their audience,
> which is unfortunate.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: filename of calling function?

2009-11-28 Thread Phlip
On Nov 28, 8:19 am, Phlip  wrote:
> Consider these two python modules:
>
> aa.py
>
> def a():
>     print '?'
>
> bb.py
>   import aa
>
> def bb():
>   aa.a()
>
> bb()
>
> How do I make the print line emit the filename of bb.py? (It could be
> anything.)

try:
raise None
except:
import sys
from traceback import extract_tb, extract_stack
frame = sys.exc_info()[2].tb_frame.f_back
calling_file = extract_stack(frame, 2)[1][0]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: filename of calling function?

2009-11-28 Thread Joel Davis
On Nov 28, 11:40 am, Phlip  wrote:
> On Nov 28, 8:19 am, Phlip  wrote:
>
>
>
> > Consider these two python modules:
>
> > aa.py
>
> > def a():
> >     print '?'
>
> > bb.py
> >   import aa
>
> > def bb():
> >   aa.a()
>
> > bb()
>
> > How do I make the print line emit the filename of bb.py? (It could be
> > anything.)
>
>         try:
>             raise None
>         except:
>             import sys
>             from traceback import extract_tb, extract_stack
>             frame = sys.exc_info()[2].tb_frame.f_back
>             calling_file = extract_stack(frame, 2)[1][0]

code works perfectly except on my system both the indexes need to be 0
(eg: "extract_stack(frame, 2)[0][0]")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: filename of calling function?

2009-11-28 Thread Phlip
On Nov 28, 9:04 am, Joel Davis  wrote:

> >         try:
> >             raise None
> >         except:
> >             import sys
> >             from traceback import extract_tb, extract_stack
> >             frame = sys.exc_info()[2].tb_frame.f_back
> >             calling_file = extract_stack(frame, 2)[1][0]
>
> code works perfectly except on my system both the indexes need to be 0
> (eg: "extract_stack(frame, 2)[0][0]")

I thought the 0 was myself, 1 my caller, etc. But tx for trying it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best performance for storage of server information for python CGI web app?

2009-11-28 Thread Aahz
In article <58e5cd75-75be-4785-8e79-490364396...@e31g2000vbm.googlegroups.com>,
davidj411   wrote:
>
>i was also thinking about using SQL Lite with one DB to store all the
>info. with this option, i would not have to worry about concurrent
>updates, but as the file size increases, i could expect performance to
>suffer again?

Depends what you mean by "suffer".  Performance always decreases as size
gets larger unless you take specific steps (such as better algorithms or
bigger hardware).  Using indexes should give SQLite reasonable
performance; you can always upgrade to a faster SQL implementation or
switch to another kind of storage.  But honestly, until you get to
millions of records, you should be fine with SQLite.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: WindowsError is not available on linux?

2009-11-28 Thread Aahz
In article ,
  wrote:
>On 07:53 pm, [email protected] wrote:
>>In article ,
>>Peng Yu   wrote:
>>>
>>>It's not clear to me whether WindowsError is available on linux or
>>>not, after I read the document.
>>
>>Here's what I told a co-worker to do yesterday:
>>
>>if os.name =3D=3D 'nt':
>>DiskError =3D (OSError, WindowsError)
>>else:
>>DiskError =3D WindowsError
>>
>>try:
>>disk_operation()
>>except DiskError:
>>logit()
>
>This isn't necessary.  WindowsError subclasses OSError.

Thanks!  Much appreciated!  (I haven't done much Windows programming in
the past -- and would have preferred to keep it that way. ;-)
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arcane question regarding white space, editors, and code collapsing

2009-11-28 Thread Aahz
In article <[email protected]>,
Ben Finney   wrote:
>Wells  writes:
>>
>> Is it... pythonic, then, to have these lines of tabs/spaces to support
>> code collapsing? Is it proper, improper, or irrelevant?
>
>It's quite improper (though syntactically null, in Python) to have
>trailing whitespace on lines. That includes blank lines.

Your parenthetical is not quite true, unfortunately.  Trailing whitespace
after a continuation backslash generates a SyntaxError.  That's the main
reason I loathe continuation lines.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing a Carriage Return in Unicode

2009-11-28 Thread Aahz
In article ,
Dennis Lee Bieber   wrote:
>On Thu, 19 Nov 2009 23:22:22 -0800, Scott David Daniels
> declaimed the following in
>gmane.comp.python.general:
>> 
>> If you've actually typed on a physical typewriter, you know that moving
>> the carriage back is a distinct operation from rolling the platen
>> forward; both operations are accomplished when you push the carriage
>> back using the bar, but you know they are distinct.  
>
>   Of course, if you are describing a /real/ /manual/ typewriter, you
>would rapidly discover that the sequence is  -- since pushing
>the bar would often trigger the line feed before it would slide the
>carriage to the right.

Often, but not always; it certainly was possible on most typewriters to
return the carriage without a line feed -- and occasionally desirable for
overstrike.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Programming Challenges for beginners?

2009-11-28 Thread Lie Ryan

On 11/28/2009 1:51 AM, n00m wrote:

On Nov 27, 1:22 pm, Jon Clements  wrote:

Of course, if you take '~' literally (len(s)<= -10001) I reckon
you've got way too many :)

Jon.


Then better: len(s)<  abs(~1)

PS It's a hard problem; so let's leave it alone


I'm not going to write it, but I guess a fairly efficient solution can 
be written with using a Trie: http://en.wikipedia.org/wiki/Trie


and iterating over its items, including partial prefixes.

Worse case scenario for creating the tree would be O(n**2) where n = 
length of string, and iterating the structure would take O(N) where N = 
number of different substring.


for "abbaz", the data structure would be:
{'a': {'b': {'b': {'a': {'z': None}}},
   'z': None,
  },
 'b': {'b': {'a': {'z': None}},
   'a': {'z': None}},
  },
 'z': None,
}

iterating the structure:
a
ab
abb
abba
abbaz
az
b
bb
bba
bbaz
ba
baz
z
---
13 (not including '')

Now, this makes me interested. How efficient it would be when len(s) == 
1... might as well write it and see. Take back what I said, give me 
a minute...

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


Re: Python Programming Challenges for beginners?

2009-11-28 Thread n00m
On Nov 28, 8:24 pm, Lie Ryan  wrote:
> Now, this makes me interested. How efficient it would be when len(s) ==
> 1... might as well write it and see. Take back what I said, give me
> a minute...

... and you can check it here: http://www.spoj.pl/problems/DISUBSTR/
I see there only one (accepted) solution in Python:
http://www.spoj.pl/ranks/DISUBSTR/lang=PYTH%202.5
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Programming Challenges for beginners?

2009-11-28 Thread n00m
PS
My straightforward C++ solution got TLE...

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

int main() {
//freopen("88.txt", "rt", stdin);
//freopen("99.txt", "wt", stdout);
int tcs;
string s;
cin >> tcs;
while (tcs-- > 0) {
cin >> s;
int n = s.size();
s = s + ' ';
vector< vector > a(256);
int ans = 0;
for (int i = n - 1; i >= 0; --i) {
int lev = 0;
vector p = a[s[i]];
vector q;
while (!p.empty()) {
q.clear();
++lev;
for (int j = 0; j < p.size(); ++j) {
if (s[p[j] + 1] == s[i + lev]) {
q.push_back(p[j] + 1);
}
}
p.swap(q);
}
a[s[i]].push_back(i);
ans += n - i - lev;
}
cout << ans << endl;
}

return 0;
}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: filename of calling function?

2009-11-28 Thread Gerard Flanagan

Phlip wrote:

Consider these two python modules:

aa.py

def a():
print '?'

bb.py
  import aa

def bb():
  aa.a()

bb()

How do I make the print line emit the filename of bb.py? (It could be
anything.)



Possibly not very reliable in every situation (doctests, other pythons, 
...) but this is what I do:



-  aa.py --
import __main__ as CALLER

def mynameis():
print CALLER.__file__

-  bb.py --

import aa

def whosthere():
aa.mynameis()

whosthere()

---

OUTPUT: bb.py


hth

G.F.

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


Re: hex int and string

2009-11-28 Thread Tim Roberts
Marco Mariani  wrote:

>luca72 wrote:
>
>> i have checked and pyscard accept also the decimal notation,
>
>I'm not sure you ever understood what the problem was, or where, but I'm 
>happy you feel like you've solved it.

+1 QOTW.  Great reply.
-- 
Tim Roberts, [email protected]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why do I get this behavior from a while loop?

2009-11-28 Thread Tim Roberts
"S. Chris Colbert"  wrote:
>
>What a newbie mistake for me to make.

Don't feel too badly about it.  Even very experienced programmers get
bitten by this issue.  Until someone points it out, it's certainly not
obvious.
-- 
Tim Roberts, [email protected]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


py2exe users

2009-11-28 Thread jim-on-linux

I have used py2exe many times with success.

My current program is completing as expected but the 
exe file fails to open.

The output file states that _imaging_gif is missing. I 
can run the program ok with IDLE but after converting 
with py2exe, the exe file just sits there.
 I'm using 2.6 on win XP.

Any Ideas?

jim-on-linux
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need clarification on -0

2009-11-28 Thread Tim Roberts
moijes12  wrote:
>
>I know the value -0 is quite meaningless and makes little sense.But I
>was just fiddling.I am unable to figure out the below result
>
 -0 and True
>0 --> (Why is this 0 and not say True or False)
 -0 and false
>0
 -0 or True
>True
>
>Could someone please provide me some resources on how these operations
>take place.I'd wanna find it out myself

Actually, there ARE computers where you might not see this result.
Virtually all of the processors on which Python runs use two's complement
arithmetic.  In two's complement, there is no separate value called -0.  0
and -0 have the same bit representation.

In one's complement, -0 and 0 have different representations.  Having spent
10 years with Control Data (the 6000 and Cyber 70/170 mainframes were all
one's complement), I am particularly sensitive to this.  Processors are
usually architected so that you don't normally see the -0, but it leads you
to think about arithmetic a bit differently.
-- 
Tim Roberts, [email protected]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scanning under windows WIA with custom settings (dpi / etc )

2009-11-28 Thread News123
r wrote:
> more *maybe useful dump?
> 
 for i in dev.Items:
>   for p in i.Properties:
>   if not p.IsReadOnly:
>   print p.Name, '->', p.Value
> 
. . .
> Horizontal Resolution -> 200
> Vertical Resolution -> 200
> Horizontal Start Position -> 0
. . .
> 
> Now how to set the values... hmmm?
> 

How to set the values? This is THE magic question.

At least I found out how to set the values in C# :

foreach (Property prop in item.Properties){
if (prop.IsReadOnly) continue;
if (prop.Name == "Horizontal Resolution")
{
 IProperty iprop = (IProperty)prop;
 Object val = 75;
 iprop.set_Value(ref val);
}
}



Below my most recent complete script:
(still not able to set params, though I can with C#)

import win32com.client, os

WIA_COM = "WIA.CommonDialog"
WIA_IMG_FORMAT_PNG = "{B96B3CAF-0728-11D3-9D7B-F81EF32E}"
WIA_COMMAND_TAKE_PICTURE="{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}"

def takePictureOrNot(dev): # cameras have to call TakePicture
for command in dev.Commands:
if command.CommandID==WIA_COMMAND_TAKE_PICTURE:
print "take PICK"
foo=dev.ExecuteCommand(WIA_COMMAND_TAKE_PICTURE)

def setImgProps(item): # here scan properties should be set
for prop in item.Properties:
if prop.IsReadOnly: continue
if(prop.Name == "Horizontal Resolution"):
res = 250
print "trying to set",prop.Name,prop,"to ",res
### unfortunately the next line (if uncommented) fails
#prop.set_Value(res)

def transferImg(dev): # set properties and scan image
i=1
image = None
for item in dev.Items:
if i==dev.Items.Count:
setImgProps(item)
image=item.Transfer(WIA_IMG_FORMAT_PNG)
break
i=i+1
return image

def scan_image_wia():
wia = win32com.client.Dispatch(WIA_COM) #  CommonDialog object
dev = wia.ShowSelectDevice()
takePictureOrNot(dev)
image = transferImg(dev)
return image

image = scan_image_wia()
fname = 'wia-test.jpg'
if os.path.exists(fname):
os.remove(fname)
image.SaveFile(fname)


bye

N


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


Re: scanning under windows WIA with custom settings (dpi / etc )

2009-11-28 Thread News123
Meanwhile I found out, why my script worked only on windows 7/Vista and
not on my XP host.

The WIA 2.0 Scripting Model is by default not installed on Windows XP.

Install instructions can be found at
http://msdn.microsoft.com/en-us/library/ms630827%28VS.85%29.aspx


My second problem (changing parameters) is still not solved in python.

bye

N

News123 wrote:
> Hi,
> 
> I'm trying to scan a document from a python 2.6 script without user
> interaction.
> 
> I found  a code snippet, that allows me to scan under Vista, but that
> doesn't allow me to select the dpi / color mode / etc.
> 
> The snippet uses win32com.client
> 
> # # script start
> import win32com.client,os
> 
> WIA_IMG_FORMAT_PNG   = "{B96B3CAF-0728-11D3-9D7B-F81EF32E}"
> WIA_COMMAND_TAKE_PICTURE = "{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}"
> 
> os.chdir('c:/temp')
> wia = win32com.client.Dispatch("WIA.CommonDialog")
> dev = wia.ShowSelectDevice()
> for command in dev.Commands:
> if command.CommandID==WIA_COMMAND_TAKE_PICTURE:
> foo=dev.ExecuteCommand(WIA_COMMAND_TAKE_PICTURE)
> i=1
> for item in dev.Items:
> if i==dev.Items.Count:
> image=item.Transfer(WIA_IMG_FORMAT_PNG)
> break
> i=i+1
> 
> image.SaveFile("test.png")
> # script end
> 
> 
> My problems are:
> 
> - This script works fine for me under Windows 7, however I'm
>   unable to   specify additional parameters, like dpi and
>   color mode.
> 
> - The script doesn't work under windows XP, though the scanner driver is
> installed. (Gimp finds the scanner (as WIA scanner)).
> Perhaps 'WIA.CommonDialig' has another name or I need to install some DLL.
> The error message is:
> 
> Traceback (most recent call last):
>   File "C:\work\python\minidemos\wia_get_simple.py", line 7, in 
> wia = win32com.client.Dispatch("WIA.CommonDialog")
>   File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line
> 95, in Dispatch
> dispatch, userName =
> dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
>   File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line
> 104, in _GetGoodDispatchAndUserName
> return (_GetGoodDispatch(IDispatch, clsctx), userName)
>   File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line
> 84, in _GetGoodDispatch
> IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
> pythoncom.IID_IDispatch)
> com_error: (-2147221005, 'Invalid class string', None, None)
> -



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


Variables with cross-module usage

2009-11-28 Thread Nitin Changlani.
Hello everyone,

I am fairly new to Python and occasionally run into problems that are almost
always resolved by referring to this mailing-list's archives. However, I
have this one issue which has got me stuck and I hope you will be tolerant
enough to help em out with it!

What I want to achieve is something like the global variables in C/C++: you
declare them in one file and "extern" them in all the files where you need
to use them. I have 3 files: one.py, two.py and three.py as below:

one.py
--
a = 'place_a'
b = 'place_b'
x = 'place_x'

myList = [a, b, 'place_c']

==

two.py
--
import one

def myFunc():
print one.x
print one.myList

==

three.py

import one
import two

def argFunc():
one.x = 'place_no_x'
one.a = 'place_no_a'
one.b = 'place_no_b'

if __name__ == '__main__':
two.myFunc()
print
argFunc()
two.myFunc()

==

Output:
---
'place_x'
['place_a', 'place_b', 'place_c']

'place_no_x'
['place_a', 'place_b', 'place_c'] (*** instead of ['place_no_a',
'place_no_b', 'place_c'] ***)

The last line in the output is what's baffling me. Can anyone please help me
know if I am doing something wrong?

Thanks in advance,
Nitin.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scanning under windows WIA with custom settings (dpi / etc )

2009-11-28 Thread MRAB

News123 wrote:

r wrote:

more *maybe useful dump?


for i in dev.Items:

for p in i.Properties:
if not p.IsReadOnly:
print p.Name, '->', p.Value


. . .

Horizontal Resolution -> 200
Vertical Resolution -> 200
Horizontal Start Position -> 0

. . .

Now how to set the values... hmmm?


Well, according to that they /aren't/ read-only because it says:

if not p.IsReadOnly:
   ^^^

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


Re: Variables with cross-module usage

2009-11-28 Thread MRAB

Nitin Changlani. wrote:

Hello everyone,

I am fairly new to Python and occasionally run into problems that are 
almost always resolved by referring to this mailing-list's archives. 
However, I have this one issue which has got me stuck and I hope you 
will be tolerant enough to help em out with it!


What I want to achieve is something like the global variables in C/C++: 
you declare them in one file and "extern" them in all the files where 
you need to use them. I have 3 files: one.py, two.py and three.py as below:


one.py
--
a = 'place_a'
b = 'place_b'
x = 'place_x'

myList = [a, b, 'place_c']

==

two.py
--
import one

def myFunc():
print one.x
print one.myList

==

three.py

import one
import two

def argFunc():
one.x = 'place_no_x'
one.a = 'place_no_a'
one.b = 'place_no_b'

if __name__ == '__main__':
two.myFunc()
print
argFunc()
two.myFunc()

==

Output:
---
'place_x'
['place_a', 'place_b', 'place_c']

'place_no_x'
['place_a', 'place_b', 'place_c'] (*** instead of ['place_no_a', 
'place_no_b', 'place_c'] ***)


The last line in the output is what's baffling me. Can anyone please 
help me know if I am doing something wrong?



What's confusing you?

myList gets its value (['place_a', 'place_b', 'place_c']) when one.py is
first imported, and you never change it after that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Variables with cross-module usage

2009-11-28 Thread Rami Chowdhury
Hi Nitin,

On Sat, Nov 28, 2009 at 14:36, MRAB  wrote:
> Nitin Changlani. wrote:
>> three.py
>> 
>> import one
>> import two
>>
>> def argFunc():
>>    one.x = 'place_no_x'
>>    one.a = 'place_no_a'
>>    one.b = 'place_no_b'
>>

I think this is what is biting you. You might expect that after
argFunc, one.x would be set to 'place_no_x' and so on. However,
Python's scoping doesn't work like that -- the name one.x is only
rebound in the function's scope, so outside of argFunc (e.g. in your
main printing code) one.x is still bound to 'place_x'.

HTH,
Rami
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Variables with cross-module usage

2009-11-28 Thread Matt Nordhoff
Rami Chowdhury wrote:
> Hi Nitin,
> 
> On Sat, Nov 28, 2009 at 14:36, MRAB  wrote:
>> Nitin Changlani. wrote:
>>> three.py
>>> 
>>> import one
>>> import two
>>>
>>> def argFunc():
>>>one.x = 'place_no_x'
>>>one.a = 'place_no_a'
>>>one.b = 'place_no_b'
>>>
> 
> I think this is what is biting you. You might expect that after
> argFunc, one.x would be set to 'place_no_x' and so on. However,
> Python's scoping doesn't work like that -- the name one.x is only
> rebound in the function's scope, so outside of argFunc (e.g. in your
> main printing code) one.x is still bound to 'place_x'.
> 
> HTH,
> Rami

Not true. argFunc does not rebind the name "one", it mutates the module
object referred to by the name "one". Since there is only one instance
of a given module*, the change is indeed reflected everywhere the "one"
module is accessed.

The problem is that argFunc does not modify (or replace) one.myList, as
MRAB said.

* Unless you do something strange like reload() or editing sys.modules
or having module available under different names...or something.
-- 
Matt Nordhoff
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Variables with cross-module usage

2009-11-28 Thread Rami Chowdhury

Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)



On Sat, Nov 28, 2009 at 14:57, Matt Nordhoff  wrote:
> Rami Chowdhury wrote:
>> Hi Nitin,
>>
>> On Sat, Nov 28, 2009 at 14:36, MRAB  wrote:
>>> Nitin Changlani. wrote:
 three.py
 
 import one
 import two

 def argFunc():
    one.x = 'place_no_x'
    one.a = 'place_no_a'
    one.b = 'place_no_b'

>>
>> I think this is what is biting you. You might expect that after
>> argFunc, one.x would be set to 'place_no_x' and so on. However,
>> Python's scoping doesn't work like that -- the name one.x is only
>> rebound in the function's scope, so outside of argFunc (e.g. in your
>> main printing code) one.x is still bound to 'place_x'.
>>
>> HTH,
>> Rami
>
> Not true. argFunc does not rebind the name "one", it mutates the module
> object referred to by the name "one". Since there is only one instance
> of a given module*, the change is indeed reflected everywhere the "one"
> module is accessed.

Ah, thanks for clarifying!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scanning under windows WIA with custom settings (dpi / etc )

2009-11-28 Thread News123
MRAB wrote:
> News123 wrote:
>> r wrote:
>>> more *maybe useful dump?
>>>
>> for i in dev.Items:
>>> for p in i.Properties:
>>> if not p.IsReadOnly:
>>> print p.Name, '->', p.Value
>>>
>> . . .
>>> Horizontal Resolution -> 200
>>> Vertical Resolution -> 200
>>> Horizontal Start Position -> 0
>> . . .
>>> Now how to set the values... hmmm?
>>>
> Well, according to that they /aren't/ read-only because it says:
> 
> if not p.IsReadOnly:
>^^^
> 
Exactly they are NOT read only, which means they are supposed to be
writable.

the python code is
for p in i.Properties:
if not.p.ISReadOnly:
# if I'm here I'm supposed to change them, but how?


the C# code, which succeds changing the property is:
foreach (Property prop in item.Properties){
if (prop.IsReadOnly) continue; // skip rest of loop
   // if property cannot
   // be modified
// now change property
if (prop.Name == "Horizontal Resolution")
{
 IProperty iprop = (IProperty)prop;
 Object val = 75;
 iprop.set_Value(ref val);
}
}



The main question is the correct python method to change the property

prop = 300 # doesn't work as it just replaces the property with an integer

prop.set_Value(res) # doesn't work as the method set_Value doesn't seem
to exist

> Traceback (most recent call last):
>   File "C:\WIA\scan_wia.py", line 41, in 
> image = scan_image_wia()
>   File "C:\WIA\scan_wia.py", line 37, in scan_image_wia
> image = transferImg(dev)
>   File "C:\WIA\scan_wia.py", line 27, in transferImg
> setImgProps(item)
>   File "C:\WIA\scan_wia.py", line 20, in setImgProps
> prop.set_Value(res)
>   File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 512, 
> in
> __getattr__
> raise AttributeError("%s.%s" % (self._username_, attr))
> AttributeError: .set_Value


bye


N


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


Re: need clarification on -0

2009-11-28 Thread Mark Dickinson
On Nov 28, 8:39 pm, Tim Roberts  wrote:
> moijes12  wrote:
>
> >I know the value -0 is quite meaningless and makes little sense.But I
> >was just fiddling.I am unable to figure out the below result
>
>  -0 and True
> >0 --> (Why is this 0 and not say True or False)
>  -0 and false
> >0
>  -0 or True
> >True
>
> >Could someone please provide me some resources on how these operations
> >take place.I'd wanna find it out myself
>
> Actually, there ARE computers where you might not see this result.
> Virtually all of the processors on which Python runs use two's complement
> arithmetic.  In two's complement, there is no separate value called -0.  0
> and -0 have the same bit representation.
>
> In one's complement, -0 and 0 have different representations.

While that's true, I think the implementation of Python is
such that the Python objects -0 and 0 should always be
indistinguishable even on machines where the underlying
architecture represents integers using ones' complement or
sign-magnitude.

At least that's certainly the intention:  there are bits of
CPython's source code that are deliberately written in
convoluted ways in order to avoid the assumption of two's
complement.  But I have a nasty suspicion that, were Python
ever unlucky enough to meet a ones' complement machine,
we'd quickly find that there were many *other* bits of the
source code that tacitly (and incorrectly) assumed a two's
complement representation.

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


Re: scanning under windows WIA with custom settings (dpi / etc )

2009-11-28 Thread John Bokma
News123  wrote:

> MRAB wrote:
>> News123 wrote:
>>> r wrote:
 more *maybe useful dump?

>>> for i in dev.Items:
 for p in i.Properties:
 if not p.IsReadOnly:
 print p.Name, '->', p.Value

[..]

> The main question is the correct python method to change the property
> 
> prop = 300 # doesn't work as it just replaces the property with an
> integer 

wild guess, but how about p.Value = 300 ?

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


Re: Variables with cross-module usage

2009-11-28 Thread Mel
Rami Chowdhury wrote:

> Hi Nitin,
> 
> On Sat, Nov 28, 2009 at 14:36, MRAB  wrote:
>> Nitin Changlani. wrote:
>>> three.py
>>> 
>>> import one
>>> import two
>>>
>>> def argFunc():
>>> one.x = 'place_no_x'
>>> one.a = 'place_no_a'
>>> one.b = 'place_no_b'
>>>
> 
> I think this is what is biting you. You might expect that after
> argFunc, one.x would be set to 'place_no_x' and so on. However,
> Python's scoping doesn't work like that -- the name one.x is only
> rebound in the function's scope, so outside of argFunc (e.g. in your
> main printing code) one.x is still bound to 'place_x'.

No, It's not like that.  MRAB had it.  The thing is, that when one.py is 
imported, it sets the name one.a to refer to a string 'place_a'.  Then a 
list named one.myList is built with one.myList[0] referring to the same 
string as one.a .  So far, so good.

Then the function argFunc is called.  It uses `one` as a name from its 
global namespace.  Inside argFunc, the names one.x and one.a are rebound to 
different strings from the ones they started with.  *But* one.myList[0] 
isn't touched, and still refers to 'place_x' like it always did.

Mel.


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


Re: need clarification on -0

2009-11-28 Thread Mark Dickinson
On Nov 28, 11:14 pm, Mark Dickinson  wrote:
> While that's true, I think the implementation of Python is
> such that the Python objects -0 and 0 should always be
> indistinguishable even on machines where the underlying
> architecture represents integers using ones' complement or
> sign-magnitude.

Hmm.  I really should think before posting.  A quick glance
at int_and, int_xor and int_or in Objects/intobject.c:

http://svn.python.org/view/python/trunk/Objects/intobject.c?view=markup

shows that Python clearly fails to be independent of the
hardware's choice of integer representation.  E.g., on a
ones' complement machine, Python would give:

>>> -1 & 1
0

but the same operation on longs would give a different
result:

>>> -1L & 1L
1L

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


Req. for comments section "Basic Data" in intro book

2009-11-28 Thread Alf P. Steinbach
I added a section on "basic data" to ch 2 of my writings, an introduction to 
programming (with Python as main language).


The intended reader is someone who is intelligent and wants to learn programming 
but knows little or nothing about it.


As before it would be nice with feedback on this.


  Format: PDF
  http://preview.tinyurl.com/ProgrammingBookP3>


Current contents:

1  Getting started.1
1.1  Python variants, implementations and distributions. 1
1.2  Download and install a Python implementation.   2
1.3  Test-drive the Python interpreter.  2
1.4  Create and run a Python console program.4
1.5  Syntax highlighting and programmers' editors.   6
1.6  Create and run a Python GUI program.7
1.7  About compilation.  9
1.8  About  standalone Windows programs & other kinds.   10
1.9  Browse the local documentation. 11
EOT 12

2  Basic concepts. 1
2.1  Super-basic concept: why programming is not DWIM.   1
2.2  Reported errors.4
2.2.1  Case-sensitity. 4
2.2.2  Syntax / compilation errors.4
2.2.3  Runtime errors / crashes.   5
2.3  A programming exploration tool: turtle graphics.6
2.4  Naming things.  8
2.4.1  Naming actions: routines.   8
2.4.2  Naming data part I: variables.  11
2.4.3  Naming data part II: routine arguments. 13
2.5  Controlling the flow of execution.  14
2.5.1  Repeating actions automatically: loops. 14
2.5.2  Basic comparisions & boolean values.16
2.5.3  Interlude I: a function graph program / about types.17
2.5.4  Automated action choices.   21
2.5.5  Value-producing (function-like) routines.   23
2.5.6  Interlude II: a graph with zeroes marked / about program structure. 26
2.5.7  Dynamically nested actions: recursive routines. 28
2.6  Basic data. 36
2.6.1  Basic fundamental types / strings & concatenation.  36
2.6.2  Indexing and single characters (+ vaguely about sequences in general). 39
2.6.3  Interlude III: a ROT-13 encryption/decryption program, refactoring. 40
2.6.4  Attributes, methods, objects.   43
2.6.5  Doc strings.44
2.6.6  Interlude IV: attribute names as strings, listing str attributes. 45
2.6.7  References. 46
EOT 49

The section on "References", 2.6.7, is about references in Python, it's not a 
list of references. :-)



Cheers,

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


Re: Some Basic questions on the use of CTRL and ALT Keys

2009-11-28 Thread Rhodri James
On Sat, 28 Nov 2009 07:30:00 -, joy99   
wrote:



On Nov 28, 5:35 am, Steven D'Aprano  wrote:

As for Alt-combinations, I don't think there is any standard for what
they are. I believe that they are operating system specific, and  
possibly

even program specific.


It seems the following site:
http://knopok.net/symbol-codes/alt-codes
is quite resourceful on Alt.


*If* (and it's a big if) you're using Windows.  Steven's point is very  
much worth bearing in mind.


--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: need clarification on -0

2009-11-28 Thread Steven D'Aprano
On Sat, 28 Nov 2009 15:14:31 -0800, Mark Dickinson wrote:

>> Actually, there ARE computers where you might not see this result.
>> Virtually all of the processors on which Python runs use two's
>> complement arithmetic.  In two's complement, there is no separate value
>> called -0.  0 and -0 have the same bit representation.
>>
>> In one's complement, -0 and 0 have different representations.
> 
> While that's true, I think the implementation of Python is such that the
> Python objects -0 and 0 should always be indistinguishable even on
> machines where the underlying architecture represents integers using
> ones' complement or sign-magnitude.

I don't think that really has any bearing on the Original Poster's 
question -- presumably on such machines, Python should treat both -0 and 
+0 as false in a boolean context and generate the same result.

When it comes to integers, I'm not aware of any mathematical or 
programming system which treats -0 and +0 as distinct entities, even if 
they have different internal representations. But the same doesn't apply 
for floats, where the IEEE standard requires that -0.0 and +0.0 be 
distinct and distinguishable (although it also requires that they compare 
as equal).



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


Re: filename of calling function?

2009-11-28 Thread Steven D'Aprano
On Sat, 28 Nov 2009 08:19:02 -0800, Phlip wrote:

> Consider these two python modules:
> 
> aa.py
> 
> def a():
> print '?'
> 
> bb.py
>   import aa
> 
> def bb():
>   aa.a()
> 
> bb()
> 
> How do I make the print line emit the filename of bb.py? (It could be
> anything.)


See the inspect module:

http://stefaanlippens.net/python_inspect


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


Re: scanning under windows WIA with custom settings (dpi / etc )

2009-11-28 Thread News123
Hi John,

John Bokma wrote:
> News123  wrote:
> 
>> MRAB wrote:
>>> News123 wrote:
 r wrote:
> more *maybe useful dump?
>
 for i in dev.Items:
> for p in i.Properties:
> if not p.IsReadOnly:
> print p.Name, '->', p.Value
> 
> [..]
> 
>> The main question is the correct python method to change the property
>>
>> prop = 300 # doesn't work as it just replaces the property with an
>> integer 
> 
> wild guess, but how about p.Value = 300 ?
> 
> John

Wild and good guess indeed.

p.Value = 300 is working.

Finally I can do WIA scans and set the parameters.




How could I have found this out without guessing?

Or phrased differently: What would be the correct way to find out what
can be done with variables returned by win32com.client s.

I tried
dir(prop)
prop.__doc__
type(prop)

and got

['_ApplyTypes_', '_FlagAsMethod', '_LazyAddAttr_', '_NewEnum',
'_Release_', '__AttrToID__', '__LazyMap__', '__call__', '__doc__',
'__eq__', '__getattr__', '__getitem__', '__init__', '__int__',
'__len__', '__module__', '__ne__', '__nonzero__', '__repr__',
'__setattr__', '__setitem__', '__str__', '_builtMethods_', '_enum_',
'_find_dispatch_type_', '_get_good_object_', '_get_good_single_object_',
'_lazydata_', '_make_method_', '_mapCachedItems_', '_oleobj_',
'_olerepr_', '_print_details_', '_proc_', '_unicode_to_string_',
'_username_', '_wrap_dispatch_']

The dynamic class used as a last resort.
The purpose of this overriding of dynamic.CDispatch is to perpetuate the
policy
of using the makepy generated wrapper Python class instead of
dynamic.CDispatch if/when possible.


and
T 

I'd like to avoid wild guessing when being confronted with another
win32.com object.


Thanks again

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


Re: Feature request: String-inferred names

2009-11-28 Thread The Music Guy
On Nov 28, 6:10 am, Lie Ryan  wrote:
> On 11/28/2009 10:38 PM, The Music Guy wrote:
>
> >> If you use it a lot, it is likely 1) you have abused class syntax for
> >> what should have been a dict or 2) what you need is to override
> >> __getattr__/__getattribute__ and __setattr__
>
> > Oh boy...here we go. :|
> > 
>
> ok, then what's your use case, AFAICT in the discussion here and
> previous ones, nobody has yet described a realistic and compelling
> situation where setattr/getattr is the best solution. That's why the
> discussion tended to end with "not used frequently enough"; simply
> because nobody can turn up with a use case to justify a new syntax,
> especially since all the proposed syntax are ugly (the most acceptable
> one, for me, is obj.[foo], still ugly but not as ugly as the others).

Alright, I'm not sure if my last message about this came through, so
I'm going to assume it didn't.

When I first started seeing @ show up in Python code, I said "what the
heck is that? It looks so weird and _ugly_. I would never try to mess
with that." But I started seeing it more and more, so I asked #python
what it was. They told me about decorators, so I looked it up in the
docs, and I thought the idea was interesting. It took me a while to
figure out exactly how they worked--and judging from messages I've
seen in #python a number of people have the same trouble understanding
them.

My point is that any particular syntax would look ugly to you only
because you haven't seen it in use enough, and haven't used it enough
yourself. But of course you haven't--it's not currently a valid
syntax. However, the ugliness would seem to go away after the syntax
had been in use for a while. And again, the EXACT syntax of the
feature can be adjusted until its "just right".

As for my specific use case, it's somewhat difficult to explain. The
general idea was to isolate a pattern that I spotted repeated in
several unrelated parts of my project. The pattern manifested itself
as a set of 4-5 methods and/or properties on a class whose objects
were designed to work in conjunction with other objects that fit a
particular behavior. These other objects had methods and properties
that were designed to interact with the first type of object in a
similar but--how should I say--"inverted" fashion.

This pattern showed up in many different classes throughout the
project, and not only that, but the code was very similar. I decided
to try to eliminate some of the code redundancy by creating a base
class for all the classes to derive from. That didn't worked out okay
for some things, but not for others. I can't remember the exact
details of the problem at this point, but I believe it had to do with
the keying/indexing protocol (ie. __getitem__, __setitem__, etc.). I
decided to keep the base class (and have since extended it), but
decided that it wasn't enough--that's when I decided to try
metaclassing. After some work I managed to recreate the object-to-
object relationship pattern that kept showing up everywhere, but in a
generic way that allowed for the names of methods and properties that
composed the pattern to vary in name and in the names that they
referenced from other objects. The code worked very well, and allowed
for the pattern to be added to any class by using a single, short line
of code (something along the lines of __class_attr = { key: value }).
Not only that, but the metaclass code itself was comprised of less
than a screenful of code after docstrings and comments had been
removed. However, the code was (and still is) very difficult to follow
simply because of the way getters and setters had to be used to
generate the methods and properties.


P.s. Lie Ryan, I appreciate your response, and I will get back to you,
but I want to make sure I reply under the right circumstances or I'll
end up putting my foot in my mouth. ^_^
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature request: String-inferred names

2009-11-28 Thread Steven D'Aprano
On Sat, 28 Nov 2009 03:38:38 -0800, The Music Guy wrote:

> Please listen. In all the time I've spent in the coding community
> (that's at least 7 years) and especially since I started paying
> attention to the Python community (2 years), I have noticed a trend:
> When one coder does something that another cannot understand, frequently
> the other will assume the former is not only doing things wrong, but is
> doing them _blatantly_ wrong. 

That's because most of the time that assumption is correct.

50% of all coders are worse than average -- and in fact since the 
distribution of coding skill is unlikely to be normally distributed, it 
may very well be true that *more* than 50% of all coders are worse than 
average. Which means that, when faced with a coder you know nothing about 
except that he is trying to do something you can't understand, merely by 
playing the odds you have at least a 50:50 chance that he's doing 
something silly.

The coders who hang around forums casting judgement are more likely like 
to better than average -- they're not just code monkeys putting in their 
eight hours days cranking out boilerplate code. They usually know what 
they're doing. They are skillful and knowledgeable -- those who aren't 
don't last long: they either leave, or they learn and become 
knowledgeable. So when people on forums suggest something is a bad idea, 
statistics is on their side, to say nothing of reasoned judgement.

Most new ideas are bad ideas. Pure statistics again -- if an idea is any 
good, somebody has probably already had it, and it has become a standard 
tool that everyone uses. Breaking code up into subroutines is such a good 
idea, and nearly every programming language has some way of breaking code 
up into subroutines. But bad ideas keep coming up over and over again, as 
they're thought of, then rejected, then somebody else comes along and 
thinks of it again. The same old bad ideas keep being raised again and 
again.



> I have caught myself making that very
> assumption many times in the past, and I've tried hard to build up an
> immunity against the impulse to make that assumption. 

Doing so reduces your chances of making uncommon false negatives at the 
cost of increasing your chances of making common false positives. 
Personally, I think it's a bad strategy, but that depends on just how 
much effort you put into giving every new idea a fair shake.


> At this point, I
> don't even believe in such a thing as a universal "wrong way" and a
> "right way" to code that applies to every circumstance. 

Well duh :)


> The way to solve a problem depends on the problem. 

Well duh again :D

But there are certain "standard", common, types of problems. Most 
problems are just variations on other problems. Very few problems are 
unique.


> When it comes to coding, there is not
> an absolute "right" way or "wrong" way--unless we're talking about, say,
> stealing closed source code without permission, or deliberately coding
> in a way that will cause problems for the end user (like causing memory
> clogs or buffer overflows and whatnot).

There is no need for "deliberately" in that sentence. If you cause 
problems like buffer overflows, you're doing it wrong. It's wrong whether 
you did so maliciously or through ignorance. Even if you document that it 
is subject to this failure mode ("don't do this"), it's still wrong.

Sometimes we do the wrong thing because sometimes it's more important to 
get a 99% solution today than a 100% solution next month, but it's still 
objectively buggy.


> All of this can be determined through common sense. And yet I continue
> to see the attitude of "my solution is the ONLY solution to your
> problem, and it doesn't matter if I don't even actually understand the
> problem." Not everyone does this, but it is a frequent enough occurence
> to be worth noting. If I had to pull a number out of my magic bag, I
> would say 4 out of 10 resposes have at least a hint of this attitude,
> and  2.5/10 where it is very obvious.

You say that as if it's a bad thing. I think it's a good thing -- most 
solutions are tried and tested, and conservatively sticking to solutions 
that are known to work is a successful solution:

* if you write code which took a lot of effort to understand, it will 
take a lot of effort to maintain;

* if you write code which only the creator understands, then if something 
happens to the creator, nobody will understand the code;

* debugging is harder than writing code in the first place, so if you 
write the cleverest code you possibly can, then you aren't clever enough 
to debug it.



[...]
> ...and I have one last thing to say. I feel very strongly that
> metaclassing is a fiercely underestimated and largely untapped source of
> good coding solutions. 

There's a reason for that -- metaclasses are *clever*. Good solutions 
should be dumb enough that even the 50% of below-average coders can use 
them. Metaclasses are hard, and because they're 

Re: Feature request: String-inferred names

2009-11-28 Thread The Music Guy
On Nov 28, 6:10 am, Lie Ryan  wrote:
> On 11/28/2009 10:38 PM, The Music Guy wrote:
>
> >> If you use it a lot, it is likely 1) you have abused class syntax for
> >> what should have been a dict or 2) what you need is to override
> >> __getattr__/__getattribute__ and __setattr__
>
> > Oh boy...here we go. :|
> > 
>
> ok, then what's your use case, AFAICT in the discussion here and
> previous ones, nobody has yet described a realistic and compelling
> situation where setattr/getattr is the best solution. That's why the
> discussion tended to end with "not used frequently enough"; simply
> because nobody can turn up with a use case to justify a new syntax,
> especially since all the proposed syntax are ugly (the most acceptable
> one, for me, is obj.[foo], still ugly but not as ugly as the others).

Alright, I'm not sure if my last message about this came through, so
I'm going to assume it didn't.

When I first started seeing @ show up in Python code, I said "what the
heck is that? It looks so weird and _ugly_. I would never try to mess
with that." But I started seeing it more and more, so I asked #python
what it was. They told me about decorators, so I looked it up in the
docs, and I thought the idea was interesting. It took me a while to
figure out exactly how they worked--and judging from messages I've
seen in #python a number of people have the same trouble understanding
them.

My point is that any particular syntax would look ugly to you only
because you haven't seen it in use enough, and haven't used it enough
yourself. But of course you haven't--it's not currently a valid
syntax. However, the ugliness would seem to go away after the syntax
had been in use for a while. And again, the EXACT syntax of the
feature can be adjusted until its "just right".

As for my specific use case, it's somewhat difficult to explain. The
general idea was to isolate a pattern that I spotted repeated in
several unrelated parts of my project. The pattern manifested itself
as a set of 4-5 methods and/or properties on a class whose objects
were designed to work in conjunction with other objects that fit a
particular behavior. These other objects had methods and properties
that were designed to interact with the first type of object in a
similar but--how should I say--"inverted" fashion.

This pattern showed up in many different classes throughout the
project, and not only that, but the code was very similar. I decided
to try to eliminate some of the code redundancy by creating a base
class for all the classes to derive from. That didn't worked out okay
for some things, but not for others. I can't remember the exact
details of the problem at this point, but I believe it had to do with
the keying/indexing protocol (ie. __getitem__, __setitem__, etc.). I
decided to keep the base class (and have since extended it), but
decided that it wasn't enough--that's when I decided to try
metaclassing. After some work I managed to recreate the object-to-
object relationship pattern that kept showing up everywhere, but in a
generic way that allowed for the names of methods and properties that
composed the pattern to vary in name and in the names that they
referenced from other objects. The code worked very well, and allowed
for the pattern to be added to any class by using a single, short line
of code (something along the lines of __class_attr = { key: value }).
Not only that, but the metaclass code itself was comprised of less
than a screenful of code after docstrings and comments had been
removed. However, the code was (and still is) very difficult to follow
simply because of the way getters and setters had to be used to
generate the methods and properties.

P.s. Ben Finney, I appreciate your response, and I will get back to
you,
but I want to make sure I reply under the right circumstances or I'll
end up putting my foot in my mouth. ^_^
-- 
http://mail.python.org/mailman/listinfo/python-list


slightly OT: Python BootCamp

2009-11-28 Thread J
Ok... so I've been re-teaching myself python, as it's been several
years since I last really used it.  And in the midst of this, my
contracting company came up to me on Friday and asked if I'd be
interested in filling a last minute vacancy in this:

http://www.otg-nc.com/python-bootcamp

It's a week long Python Bootcamp.  I figured, free class, a week where
I'll not have to actually go to work, AND I'll get paid, sure!

So I was just wondering if any of you have attended this one, or one
like it, and what your impressions were.  I've attended a few before,
and found them widely different.  The RH300, for example, was
blisteringly fast and really just touches on things, so if you don't
already know Red Hat inside and out, you'll never survive.  The VMWare
VCP courses, on the other hand, were fairly languid by contrast and
seemed to flow in a less frantic state.

So I figured this would be the place to ask.

And if it matters, I do have an educational background in programming
(VB, C++, C, Java, etc) but my professional background has mostly been
limited to Bash, OCCASIONAL C, and now a touch of Python, so I am not
new to programming and OO programming, just not as proficient as I
would like to be...

Cheers
Jeff

-- 

Jonathan Swift  - "May you live every day of your life." -
http://www.brainyquote.com/quotes/authors/j/jonathan_swift.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Python3 - encoding issues

2009-11-28 Thread DreiJane
Hello,

at first i must beg the pardon of those from you, whose mailboxes got
flooded by my last announcement of depikt. I myself get no emails from
this list, and when i had done my corrections and posted each of the
sligthly improved versions, i wasn't aware of the extra emails that
produces. Sorry !

I read here recently, that some reagard Python3 worse at encoding
issues than former versions. For me, a German, quite the contrary is
true. The automatic conversion without an Exception from before 3 has
caused pain over pain during the last years. Even some weeks before it
happened, that pygtk suddenly returned utf-8, not unicode, and my
software had delivered a lot of muddled automatically written emails,
before i saw the mess. Python 3 would have raised Exceptions - however
the translation of my software to 3 has just begun.

Now there is a concept of two separated worlds, and i have decided to
use bytes for my software. The string representation, that output
needs anyway, and with depikt and a changed apsw (file reads anyway)
or other database-APIs (internally they all understand utf-8)  i can
get utf-8 for all input too.

This means, that i do not have the standard string methods, but
substitutes are easily made. Not for a subclass of bytes, that
wouldn't have the b"" initialization. Thus only in form of
functions. Here are some of my utools:

u0 = "".encode('utf-8')
def u(s):
if type(s) in (int, float, type): s = str(s)
if type(s) == str: return s.encode("utf-8")
if type(s) == bytes: # we keep the two worlds cleanly separated
raise TypeError(b"argument is bytes already")
raise TypeError(b"Bad argument for utf-encoding")

def u_startswith(s, test):
try:
if s.index(test) == 0: return True
except:# a bit frisky perhaps
return False

def u_endswith(s, test):
if s[-len(test):] == test: return True
return False

def u_split(s, splitter):
ret = []
while s and splitter in s:
if u_startswith(s, splitter):
s = s[len(splitter):]; continue
ret += s[:s.index[splitter]]
return ret + [s]

def u_join(joiner, l):
while True:
if len(l) in (0,1): return l
else: l = [l[0]+joiner+l[1]]+l[2:]

(not all with the standard signatures). Writing them is trivial. Note
u0 - unfortunately b"" doesn't at all work as expected, i had to learn
the hard way.

Looking more close to these functions one sees, that they only use the
sequence protocol. "index" is in the sequence protocol too now - there
the library reference has still to be updated. Thus all of these and
much more string methods could get to the sequence protocol too
without much work - then nobody would have to write all this. This
doesn't only affect string-like objects: split and join for lists
could open interesting possibilities for list representations of trees
for example.

Does anybody want to make a PEP from this (i won't do so) ?

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


Re: Variables with cross-module usage

2009-11-28 Thread Nitin Changlani.
Thanks for the reply MRAB, Rami, Matt and Mel,

I was assuming that since one.myList0] = one.a, the change in one.a will
ultimately trickle down to myList[0] whenever myList[0] is printed or used
in an expression. It doesn't come intuitively to me as to why that should
not happen. Can you kindly suggest what is the correct way to go about it?

Nitin.

>
>
>
> > Hi Nitin,
> >
> > On Sat, Nov 28, 2009 at 14:36, MRAB  wrote:
> >> Nitin Changlani. wrote:
> >>> three.py
> >>> 
> >>> import one
> >>> import two
> >>>
> >>> def argFunc():
> >>> one.x = 'place_no_x'
> >>> one.a = 'place_no_a'
> >>> one.b = 'place_no_b'
> >>>
> >
> > I think this is what is biting you. You might expect that after
> > argFunc, one.x would be set to 'place_no_x' and so on. However,
> > Python's scoping doesn't work like that -- the name one.x is only
> > rebound in the function's scope, so outside of argFunc (e.g. in your
> > main printing code) one.x is still bound to 'place_x'.
>
> No, It's not like that.  MRAB had it.  The thing is, that when one.py is
> imported, it sets the name one.a to refer to a string 'place_a'.  Then a
> list named one.myList is built with one.myList[0] referring to the same
> string as one.a .  So far, so good.
>
> Then the function argFunc is called.  It uses `one` as a name from its
> global namespace.  Inside argFunc, the names one.x and one.a are rebound to
> different strings from the ones they started with.  *But* one.myList[0]
> isn't touched, and still refers to 'place_x' like it always did.
>
>Mel.
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python3 - encoding issues

2009-11-28 Thread Benjamin Peterson
DreiJane  h-labahn.de> writes:
> Does anybody want to make a PEP from this (i won't do so) ?

I will answer this query with a little interactive prompt session:

$ python3
Python 3.1.1 (r311:74480, Nov 14 2009, 13:56:40)
[GCC 4.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data = b"Good, morning"
>>> data.startswith(b"Good")
True
>>> data.split(b", ")
[b'Good', b'morning']
>>> x = data.split(b", ")
>>> b", ".join(x)
b'Good, morning'

Bytes already have the basic string functions!



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


Re: slightly OT: Python BootCamp

2009-11-28 Thread Aahz
In article ,
J   wrote:
>
>Ok... so I've been re-teaching myself python, as it's been several
>years since I last really used it.  And in the midst of this, my
>contracting company came up to me on Friday and asked if I'd be
>interested in filling a last minute vacancy in this:
>
>http://www.otg-nc.com/python-bootcamp

No opinion, but just wanted to note that this is completely ON-topic for
comp.lang.python.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/HTML integration: phileas v0.3 released

2009-11-28 Thread Aahz
In article <6ded5cc9-5491-43d3-849c-17fcfaaec...@k17g2000yqh.googlegroups.com>,
papa hippo   wrote:
>
>The prime goal of 'phileas' is to enable html code to be seamlessly
>included in python code in a natural looking syntax, without resorting
>to templatng language.
>
>see:
>
>http://larry.myerscough.nl/phileas_project/

Why would I want to use this instead of Quixote?
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python3 - encoding issues

2009-11-28 Thread DreiJane
Ohhh - that's nice. But no words of that in the library reference
here:

http://docs.python.org/3.1/library/stdtypes.html#sequence-types-str-bytes-bytearray-list-tuple-range

Still this fails:

>>> a = (1,2,3,4)
>>> print(a.startswith((1,2)))
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'tuple' object has no attribute 'startswith'

Still methods of this kind would have a better place in the sequence
protocol.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Variables with cross-module usage

2009-11-28 Thread Nitin Changlani
Thanks for the reply MRAB, Rami, Matt and Mel,

I was assuming that since one.myList0] = one.a, the change in one.a will
ultimately trickle down to myList[0] whenever myList[0] is printed or used
in an expression. It doesn't come intuitively to me as to why that should
not happen. Can you kindly suggest what is the correct way to go about it?

Nitin.

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


Re: Feature request: String-inferred names

2009-11-28 Thread Steven D'Aprano
On Sat, 28 Nov 2009 17:22:27 -0800, The Music Guy wrote:

> As for my specific use case, it's somewhat difficult to explain. The
> general idea was to isolate a pattern that I spotted repeated in several
> unrelated parts of my project. The pattern manifested itself as a set of
> 4-5 methods and/or properties on a class whose objects were designed to
> work in conjunction with other objects that fit a particular behavior.
> These other objects had methods and properties that were designed to
> interact with the first type of object in a similar but--how should I
> say--"inverted" fashion.
> 
> This pattern showed up in many different classes throughout the project,
> and not only that, but the code was very similar. I decided to try to
> eliminate some of the code redundancy by creating a base class for all
> the classes to derive from. That didn't worked out okay for some things,
> but not for others. I can't remember the exact details of the problem at
> this point, but I believe it had to do with the keying/indexing protocol
> (ie. __getitem__, __setitem__, etc.). I decided to keep the base class
> (and have since extended it), but decided that it wasn't enough--that's
> when I decided to try metaclassing. After some work I managed to
> recreate the object-to- object relationship pattern that kept showing up
> everywhere, but in a generic way that allowed for the names of methods
> and properties that composed the pattern to vary in name and in the
> names that they referenced from other objects.

Removing code redundancy is all very well, but beware of turning into an 
architecture astronaut:

http://www.joelonsoftware.com/articles/fog18.html

There is such a thing as over-generalisation -- if you're having to 
struggle to get the abstract code working abstractly enough, you're 
probably over-generalising. 


> The code worked very
> well, and allowed for the pattern to be added to any class by using a
> single, short line of code (something along the lines of __class_attr =
> { key: value }). Not only that, but the metaclass code itself was
> comprised of less than a screenful of code after docstrings and comments
> had been removed. However, the code was (and still is) very difficult to
> follow simply because of the way getters and setters had to be used to
> generate the methods and properties.

That's good evidence that you've over-generalised.



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


Re: Python3 - encoding issues

2009-11-28 Thread Benjamin Peterson
DreiJane  h-labahn.de> writes:

> 
> Ohhh - that's nice. But no words of that in the library reference
> here:
> 
>
http://docs.python.org/3.1/library/stdtypes.html#sequence-types-str-bytes-bytearray-list-tuple-range

That's because it's here:
http://docs.python.org/3.1/library/stdtypes.html#bytes-and-byte-array-methods

> 
> Still this fails:
> 
> >>> a = (1,2,3,4)
> >>> print(a.startswith((1,2)))
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'tuple' object has no attribute 'startswith'
> 
> Still methods of this kind would have a better place in the sequence
> protocol.

You are welcome to bring this idea to the python-ideas list, just know that it
has a small chance of being accepted.




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


Re: Feature request: String-inferred names

2009-11-28 Thread inhahe
i like this idea (i posted some thoughts on it in the blog, but it's not
approved yet as of this writing)

in short, i suggested extending the idea to make it more a) generalized, b)
simple, c) intuitive, and d) flexible.

so instead of just using $ for attributes, you could use it anywhere you
define or reference a name.

as in..

class $a: pass

or

$a = 1

also, you might want to do something like this
b = ["zero", "one"]

$b[0] = 0

but that's ambiguous, so you need some sort of grouping mechanism
like for example

${b[0]} = 0

although "$(b[0]) = 0" might be just as reasonable.

also maybe:

b = 'bar'

foo$b = 'baz'
print foobar
#prints baz

${b}foo = 'baz'
print barfoo
#prints baz

$foo{b}baz = 1
print foobarbaz
#prints 1

but i know that last idea is getting way into php-land and probably isn't
(quote-unquote) necessary.


i know a lot of people would probably hate this idea with a passion.  i tend
to be more liberal when it comes to adding concision and dynamicism in a
language, although that could be just because it's too tempting; i.e., maybe
it's only because somebody drew a line somewhere that we're coding in Python
instead of K.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Imitating "tail -f"

2009-11-28 Thread Aahz
In article ,
Matt Nordhoff   wrote:
>Jason Sewall wrote:
>>
>> FWIW, GNU tail on Linux uses inotify for tail -f:
>
>Some other operating systems have similar facilities, e.g. FSEvents on OS X.

Having spent some time with FSEvents, I would not call it particularly
similar to inotify.  FSEvents only works at the directory level.  Someone
suggested pnotify the last time this subject came up, but I haven't had
time to try it out.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Is It A Directory

2009-11-28 Thread Lawrence D'Oliveiro
When doing recursive directory traversal, sometimes you want to follow 
symlinks that point at other directories, and sometimes you don’t. Here’s a 
routine that you can use to check whether a path specifies a directory, with 
the option to treat a symlink to a directory as a directory, or not:

import os
import stat

def isdir(path, followsymlink) :
"""returns true iff path specifies a directory. A symlink is followed
iff followsymlink."""
return stat.S_ISDIR((os.lstat, os.stat)[followsymlink](path).st_mode)
#end isdir   

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


Re: Variables with cross-module usage

2009-11-28 Thread Steven D'Aprano
On Sat, 28 Nov 2009 22:18:11 -0500, Nitin Changlani wrote:

> Thanks for the reply MRAB, Rami, Matt and Mel,
> 
> I was assuming that since one.myList0] = one.a, the change in one.a will
> ultimately trickle down to myList[0] whenever myList[0] is printed or
> used in an expression. It doesn't come intuitively to me as to why that
> should not happen. Can you kindly suggest what is the correct way to go
> about it?


You are confusing *names* and *objects*. The presence or absence of a 
module qualifier is irrelevant, so for simplicity I will avoid it. I will 
use ` ` quotation marks to refer to names, to avoid confusing them with 
strings.


The Python statement 

a = "some text"

creates a name `a` which is bound to the object "some text".

myList[0] = a

stores the object bound to the name `a` to the first position of myList, 
not the name itself. So myList[0] ends up being "some text", but it has 
no idea whether it came from the name `a` or somewhere else.

Then when you execute:

a = "different text"

the name `a` is bound to the object "different text". But this doesn't 
affect myList[0] at all, because you're not changing the object "some 
text" -- strings are immutable and can't be changed.



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


Re: need clarification on -0

2009-11-28 Thread Ned Deily
In article <[email protected]>,
 Steven D'Aprano  wrote:
> When it comes to integers, I'm not aware of any mathematical or 
> programming system which treats -0 and +0 as distinct entities, even if 
> they have different internal representations.

A documented feature of most FORTRAN run-time libraries on the Control 
Data 6600/70/170 family (a one's-complement architecture cited earlier 
by Tim Roberts) was to convert a blank numeric input field (i.e. 
consisting of all space characters) to minus zero.   Many programmers 
took advantage of that, using a test for -0 as an easy, though not 100% 
foolproof, test for a missing numeric value.

-- 
 Ned Deily,
 [email protected]

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


Best strategy for converting to Python

2009-11-28 Thread Poker Player
I have a calculator program that is written in Visual C# and I would like to
convert it to python using any method possible.

 

I am thinking I have to rewrite the GUI and use the Visual C# as I go to
make sure I am doing it right but I have no idea as to how this should work
when converting a program like this. 

I almost think I could start from scratch and write the whole thing that way
but I want to make sure I do not lose any of the important
functionality/features.

 

I can provide any details needed I just don't want to jump in without some
sort of guidance.

 

Thanks,

Spencer

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


python and vc numbers

2009-11-28 Thread Daniel Dalton
Hi,

I have a very simple problem, but I can't work out the answer. How do I
return the current tty number in python? eg. what function/module should
I use to figure out what tty my program was invoked from?

Thanks

-- 
Cheers,
Dan

http://members.iinet.net.au/~ddalton/



signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list