Re: [Tutor] Variables and constants [was Re: working with strings inpython3]

2011-04-19 Thread Steven D'Aprano

bod...@googlemail.com wrote:

And presumably cleans up the leftover object with the value of 42 when it 
changes to point at the 43 object?


In principle, yes, the garbage collector will destroy the no-longer used 
object 42 once nothing is pointing to it any more.


But in practice, Python caches "small integers", where the definition of 
small depends on which version of Python you are using, on the basis 
that it's better to hang onto them in a cache for re-use than to keep 
making and destroying them over and over again. This is a classic "time 
versus space" trade-off: using extra memory to save time.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Variables and constants [was Re: working with strings inpython3]

2011-04-19 Thread Steven D'Aprano

Joel Goldstick wrote:


If a value has no name bound to it, python figures that out and destroys it


Not quite... if there is no name, or any other reference, then the 
garbage collector will destroy it. But it doesn't have to be a name: 
anonymous objects can live inside lists, or dicts, or sets, or as values 
in functions, etc.




--
Steven



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] wxPython parent classes

2011-04-19 Thread Alan Gauld


"Eric Stevens"  wrote
I've been noticing that in all the example codes I have seen, when 
someone
creates container, x,  inside of a frame or other container class, 
y, they

always seem to create an instance of wx.Panel first


You got an answer this time, but you will probably get better results
posting wxPython questions on the wxPython mailing list/forums. 
Posting

here is more a matter of luck if anyone reading happens to use wx...

Alan G.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with strings in python3

2011-04-19 Thread Alan Gauld

"Rance Hall"  wrote


Variables are variable, that's why we call them variable.


Yes, but Programming variables(*) are variable in the sense 
that they can represent different values over time. That is 
not the same as requiring the values themselves to change.


The idea of immutable strings variables blurs the 
line between these two mathematical concepts 


Not at all. In math you can have a variable reference 
the number 42. Later the same variable may represent 
a different number, 66 say. But 66 and 42 are different, 
immutable numbers. It is no different with strings in Python.
A variable can refer to 'foo'; at one point and 'bar' at another. 
But 'foo' and 'bar' (and indeed 'foobar') are different values 
just as 42, 66 and 108 are different numbers. Python 
strings act like numbers in that regard.



variable is variable or mutable, where a keyname can not be.


variables are always variable but only some values 
are mutable You are conflating variables and values. 
Strings are values (or objects if you prefer) and (arbitrarily) 
chosen to be immutable by Guido. Variables are associated 
with values and the values with which they are associated 
can, and do, change.


(*)Note that variables in programming are treated differently 
from traditional math variables in that math variables are usually 
considered as symbols for a constant, unchanging value. 
It is unusual in math to say


Let x = 42
 stuff 
Let x = 66

We would introduce a new variable for the new value.
But that idiom is very common in programming generally.


HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with strings in python3

2011-04-19 Thread Alan Gauld


"Rance Hall"  wrote


String formatting doesn't work for me in this case
as the message is sort of dynamic.


I don;t understand that, string formatting is probably
the most dynamic way of constructing strings
there is, its designed for dynamic data! If your data
is really dynamic the only two ways that make sense
are joining lists or using format strings. The latter
combines dynamic with output control too.


Way too much logic around printing a statement.


I don;t see how format strings can be a problem
combined with complex logic, string contatenation
would be much more complex to deal with.


A list might make sense, but printing a message
one word at a time ...


The list doesn't need to contaain single words - unless
that is really how dynamic your output is - but even
then it will be faster than string concatenation - more
typically the list will contain sentence fragments

You can even use indirection for more dynamic use cases:


# assume gender and hour are dynamically input
# or calculated elsewhere
stringList = ["Good", "Morning", "Afternoon","Evening", 
"Night","Sir","Madam"]


fields = []
if 6 < hour < 12:  fields.append(1)
elif 12 <= hours < 18: fields.append(2)
elif 18 <= hours <=23 fields.append(3)
else: fields.append(4)

if gender == "Male": fields.append(5)
else: fields.append(6)

print( " ".join([stringList[n] for n in fields]) )


But are CLI apps so rare that this sort of thing just doesn't happen
anymore?  This seems like such a basic thing and deprecating it 
seems

rather harsh.


They aren't rare and concatenation isn't deprecated,
but there are other alternatives that may be more
suitable depending on your usage.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Variables and constants [was Re: working with strings inpython3]

2011-04-19 Thread Marc Tompkins
On Tue, Apr 19, 2011 at 2:37 PM, Joel Goldstick wrote:

>
> On Tue, Apr 19, 2011 at 3:32 PM,  wrote:
>
>> And presumably cleans up the leftover object with the value of 42 when it
>> changes to point at the 43 object?
>>
>> Or does it leave all changes in memory until the program exits?
>>
>
> If a value has no name bound to it, python figures that out and destroys it
>

This is called "garbage collection" - one of those terms you may hear in the
background for ages before you realize what it refers to.  Automatic memory
allocation / garbage collection are among the greatest productivity
advantages in using languages like Python; your code probably won't be as
efficient as if you'd painstakingly written all the malloc()'s and free()'s
yourself, but you'll save many hours of drudgery - and far more importantly,
many many hours of debugging to find the places where you forgot something.

The other advantage, of course, is that Python is awesome.  But you knew
that already.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with strings in python3

2011-04-19 Thread Alan Gauld

"Rance Hall"  wrote


Ok so I know what I am doing is deprecated


I'm not aware of string concatenation being deprecated.
Ols string formatting is deprecated in the sense that the new
string format() method will replace it, but I don't even
expect to see that any time soon - too much old code
uses formatting.


the replacement must be awkward cause I'm not getting it.


There is no replacement but there are alternatives.
But the choice of when to use concatenation or when to
use the other methods is usually a matter of style and,
occasionally, of performance


message = "Bah."

if test:
  message = message + " Humbug!"


Apart from maybe using += instead of + I see nothing
wrong with this usage.


print(message)


Although you could have missed it out and gone straight to:

print(message,'Humbug!')

Since print will concatenate it's output for you.

I'm sure this is not the way we are supposed to augment strings like 
this.


It works fine for me, and I don't recall seeing anything saying
not to do it. It carries a small performance and memory overhead
but thats only a problem in a tight or long loop or if dealing with
enormous strings (say megabyte size)

maybe there is string.append() method or something I should be using 
instead?


You can use the join method of lists which is faster but less obvious:

" ".join([message,'Humbug!"])

Or you can use string formatting

"{1}{2}".format(message,"Humbug!")

I'm not sure how the format() method compares to join for speed,
the old style formatting seemed about equivalent in my highly
unscientific testing...I haven't tried the new style - I don;t care 
that much!.



In my case the optional extra parts are always at the end of the
current value of the string.


If you only do that operation "occasionally" then using '+' is OK.
Don't get overly anxious. Readability counts too.


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Variables and constants [was Re: working with strings inpython3]

2011-04-19 Thread Joel Goldstick
On Tue, Apr 19, 2011 at 3:32 PM,  wrote:

> And presumably cleans up the leftover object with the value of 42 when it
> changes to point at the 43 object?
>
> Or does it leave all changes in memory until the program exits?
>
> Bodsda.
> Sorry for top posting, my phone won't let me change it
> Sent from my BlackBerry® wireless device
>
> -Original Message-
> From: Steven D'Aprano 
> Sender: tutor-bounces+bodsda=ubuntu@python.org
> Date: Wed, 20 Apr 2011 04:24:03
> To: tutor
> Subject: [Tutor] Variables and constants [was Re: working with strings in
>  python3]
>
> Rance Hall wrote:
>
> > Variables are variable, that's why we call them variable.
> > Constants are constant, and that's why we call them constant.
>
> And Python has neither variables nor constants in the sense that (say)
> Pascal, C or Fortran have, even though we often use the same words.
>
> The differences are quite deep, but they're also subtle.
>
> In classic programming languages with variables and/or constants, the
> model is that names like "x" refer to *memory locations*. If the name is
> a variable, the compiler will allow you to mutate the value stored at
> that memory location; if the name is a constant, it won't. But once a
> name "x" is associated with memory location (say) 123456, it can never
> move. But note that the "variability" or "constantness" is associated
> with the *name* (the memory location), not the value.
>
> In languages like Python, names are associated with values, without
> reference to memory locations. In this case, the "variability" or
> "constantness" is associated with the *value*, not the name.
>
> Consider x = 42; x = x+1. In Pascal, C or Fortran, this will actually
> change a block of memory that had the value 42 into 43 instead:
>
> The name x points to a memory location with value 42.
> Leave the name pointing to the same place, but change the value to 43
> instead.
>
> In Python, the situation is different:
>
> The name x points to an object with value 42.
> Leave the object 42 alone, but change the name x to point to an object
> with value 43 instead.
>
>
>
> --
> Steven
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

If a value has no name bound to it, python figures that out and destroys it

-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Variables and constants [was Re: working with strings inpython3]

2011-04-19 Thread bodsda
And presumably cleans up the leftover object with the value of 42 when it 
changes to point at the 43 object? 

Or does it leave all changes in memory until the program exits?

Bodsda.
Sorry for top posting, my phone won't let me change it 
Sent from my BlackBerry® wireless device

-Original Message-
From: Steven D'Aprano 
Sender: tutor-bounces+bodsda=ubuntu@python.org
Date: Wed, 20 Apr 2011 04:24:03 
To: tutor
Subject: [Tutor] Variables and constants [was Re: working with strings in
 python3]

Rance Hall wrote:

> Variables are variable, that's why we call them variable.
> Constants are constant, and that's why we call them constant.

And Python has neither variables nor constants in the sense that (say) 
Pascal, C or Fortran have, even though we often use the same words.

The differences are quite deep, but they're also subtle.

In classic programming languages with variables and/or constants, the 
model is that names like "x" refer to *memory locations*. If the name is 
a variable, the compiler will allow you to mutate the value stored at 
that memory location; if the name is a constant, it won't. But once a 
name "x" is associated with memory location (say) 123456, it can never 
move. But note that the "variability" or "constantness" is associated 
with the *name* (the memory location), not the value.

In languages like Python, names are associated with values, without 
reference to memory locations. In this case, the "variability" or 
"constantness" is associated with the *value*, not the name.

Consider x = 42; x = x+1. In Pascal, C or Fortran, this will actually 
change a block of memory that had the value 42 into 43 instead:

The name x points to a memory location with value 42.
Leave the name pointing to the same place, but change the value to 43 
instead.

In Python, the situation is different:

The name x points to an object with value 42.
Leave the object 42 alone, but change the name x to point to an object 
with value 43 instead.



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] wxPython parent classes

2011-04-19 Thread Mark Weil
wx.Panel provides better cross-platform reliability, so it's fairly standard
practice to go with a Panel in a Frame, and place the buttons, etc. on the
panel.



On Tue, Apr 19, 2011 at 11:59 AM, Eric Stevens wrote:

> I've been noticing that in all the example codes I have seen, when someone
> creates container, x,  inside of a frame or other container class, y, they
> always seem to create an instance of wx.Panel first and then use that
> instance as the parent class of container x. I have been just placing 'self'
> in there, however, letting the class I am creating (whether it be a wx.Frame
> subclass, wx.ScrolledWindow subclass, etc) be the parent class of any other
> wx.Window class I instantiate inside that class. Is one way better than the
> other, and if so, why? Thanks.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] wxPython parent classes

2011-04-19 Thread Eric Stevens
I've been noticing that in all the example codes I have seen, when someone
creates container, x,  inside of a frame or other container class, y, they
always seem to create an instance of wx.Panel first and then use that
instance as the parent class of container x. I have been just placing 'self'
in there, however, letting the class I am creating (whether it be a wx.Frame
subclass, wx.ScrolledWindow subclass, etc) be the parent class of any other
wx.Window class I instantiate inside that class. Is one way better than the
other, and if so, why? Thanks.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Variables and constants [was Re: working with strings in python3]

2011-04-19 Thread Steven D'Aprano

Rance Hall wrote:


Variables are variable, that's why we call them variable.
Constants are constant, and that's why we call them constant.


And Python has neither variables nor constants in the sense that (say) 
Pascal, C or Fortran have, even though we often use the same words.


The differences are quite deep, but they're also subtle.

In classic programming languages with variables and/or constants, the 
model is that names like "x" refer to *memory locations*. If the name is 
a variable, the compiler will allow you to mutate the value stored at 
that memory location; if the name is a constant, it won't. But once a 
name "x" is associated with memory location (say) 123456, it can never 
move. But note that the "variability" or "constantness" is associated 
with the *name* (the memory location), not the value.


In languages like Python, names are associated with values, without 
reference to memory locations. In this case, the "variability" or 
"constantness" is associated with the *value*, not the name.


Consider x = 42; x = x+1. In Pascal, C or Fortran, this will actually 
change a block of memory that had the value 42 into 43 instead:


The name x points to a memory location with value 42.
Leave the name pointing to the same place, but change the value to 43 
instead.


In Python, the situation is different:

The name x points to an object with value 42.
Leave the object 42 alone, but change the name x to point to an object 
with value 43 instead.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with strings in python3

2011-04-19 Thread Steven D'Aprano

Rance Hall wrote:

On Mon, Apr 18, 2011 at 9:50 PM, Marc Tompkins  wrote:

On Mon, Apr 18, 2011 at 6:53 PM, Rance Hall  wrote:


I'm going to go ahead and use this format even though it is deprecated
and then later when we upgrade it I can fix it.


And there you have your answer.


A list might make sense, but printing a message one word at a time
doesn't seem to me like much of a time saver.


Did you try my example code?  It doesn't "print a message one word at a
time"; any time you print " ".join(message), you get the whole thing.  Put a
\n between the quotes, and you get the whole thing on separate lines.



I think you misunderstood me, I simply meant that the print "
".join(message) has to parse through each word in order to get any
output, I didn't mean to suggest that you got output one word at a
time.  Sorry for the confusion.


Well, yes, but you have to walk over each word at some point. The join 
idiom merely puts that off until just before you need the complete 
string, instead of walking over them over and over and over again. 
That's why the join idiom is usually better: it walks over each string 
once, while repeated concatenation has the potential to walk over each 
one dozens, hundreds or thousands of times (depending on how many 
strings you have to concatenate). To be precise: if there are N strings 
to add, the join idiom does work proportional to N, while the repeated 
concatenation idiom does work proportional to N*N.


This is potentially *so* catastrophic for performance that recent 
versions of CPython actually go out of its way to protect you from it 
(other Python, like Jython, IronPython and PyPy might not). But with a 
little bit of extra work, we can shoot ourselves in the foot and see how 
bad *repeated* string concatenation can be:



>>> from timeit import Timer
>>>
>>> class Magic:
... def __add__(self, other):
... return other
...
>>> m = Magic()
>>> strings = ['a']*1
>>>
>>> t1 = Timer('"".join(strings)', 'from __main__ import strings')
>>> t2 = Timer('sum(strings, m)', 'from __main__ import strings, m')
>>>
>>> t1.timeit(1000)  # one thousand timing iterations
1.0727810859680176
>>> t2.timeit(1000)
19.48655891418457


In Real Life, the performance hit can be substantial. Some time ago 
(perhaps a year?) there was a bug report that copying files over the 
network was *really* slow in Python. By memory, the bug report was that 
to download a smallish file took Internet Explorer about 0.1 second, the 
wget utility about the same, and the Python urllib module about TEN 
MINUTES. To cut a long story short, it turned out that the module in 
question was doing repeated string concatenation. Most users never 
noticed the problem because Python now has a special optimization that 
detects repeated concatenation and does all sorts of funky magic to make 
it smarter and faster, but for this one user, there was some strange 
interaction between how Windows manages memory and the Python optimizer, 
the magic wasn't applied, and consequently the full inefficiency of the 
algorithm was revealed in all it's horror.



Bottom line: unless you have actually timed your code and have hard 
measurements showing different, you should always expect repeated string 
concatenation to be slow and the join idiom to be fast.




--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: working with strings in python3

2011-04-19 Thread Marc Tompkins
Forgot to send to group.  Grrr.

-- Forwarded message --
From: Marc Tompkins 
Date: Tue, Apr 19, 2011 at 10:01 AM
Subject: Re: [Tutor] working with strings in python3
To: Rance Hall 


On Tue, Apr 19, 2011 at 6:44 AM, Rance Hall  wrote:

>  > Bottom line: Python is not BASIC.  In BASIC, strings aren't immutable,
> so in-place string concatenation doesn't carry (much of) a performance
> > penalty.  In Python, it will make your program unnecessarily slow.  I
> think you're under the impression that "deprecation" is a value judgment, or
> that
> > "message = message + foo" is deprecated because it looks like BASIC
> syntax.
> > Neither is true.
>
> Again a little misunderstanding.  I didn't mean BASIC the programming
> language.  I forgot all I knew about that language long ago.  I mean basic
> in the fundamental concept sense.
>

No, I wasn't conflating 'basic' and BASIC, nor did I think you were - I was
just using BASIC as the first example I could think of where "message =
message + foo" is the standard way to concatenate strings.  You can't do it
that way in C or Perl or assembler;  it's not recommended in Java for much
the same reason as in Python (
http://www.ibm.com/developerworks/websphere/library/bestpractices/string_concatenation.html);
I don't remember what I used to do in COBOL; the only example that came to
mind was BASIC.  Which is a different language from Python, and different
rules apply, which was the only point I was trying to make.

Variables are variable, that's why we call them variable.
> Constants are constant, and that's why we call them constant.
>
> There's an old programmer's saying: "Constants aren't, and variables
don't."  More to the point, though, Python was designed from the ground up
as an object-oriented language (as opposed to a conventional language with
object support bolted on as an afterthought); both constants and variables
are actually objects, and act differently than they do in a non-OO
language.

> We may ask ourselves "why did Guido decide to make strings immutable in
> the first place?"; probably the best reason is "so that strings can be used
> as keys in a dictionary", but since I'm not Guido - not even Dutch! - I
> really can't speak for him.
>
> I'm not sure I buy this explanation as strings have been used as keys in
> dictionaries or "associative arrays" for a long time, a string variable is
> variable or mutable, where a keyname can not be.
>

Reread the two parts of your own sentence - "strings have been used as
keys... for a long time" and "a string variable is variable or mutable,
where a keyname can not be".  It's like a Zen koan.  Reconcile those two
concepts and I think you will have grasped the Buddha-nature of Python
strings.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Type error: must be string or read-only character buffer, not seq

2011-04-19 Thread Kann Vearasilp
Thanks Peter,

That just fixes my problem. : )

Kann

On Tue, Apr 19, 2011 at 5:29 PM, Peter Otten <__pete...@web.de> wrote:
> Kann Vearasilp wrote:
>
>> I tried concatenating string variables with multiple strings and have the
>> file handle write the statement into a file. I don't know why I always get
>> the type error: must be string or read-only character buffer, not seq
>> error. I tried casting the whole new concatenated string using str(), but
>> was not successful as well. Do you have any clue why this happen?
>
>>  52         str(statement)
>>  53         insert.write(statement)
>
> Line 52 doesn't do what you think it does -- it converts statement to a
> string and then discards the result.
>
> Try
>
> statement = str(statement)
> insert.write(statement)
>
> or
>
> insert.write(str(statement))
>
> instead.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] win32com and python

2011-04-19 Thread Tim Golden

On 19/04/2011 15:53, Pierre Barthelemy wrote:

The problem i have is that, often, while the script is running, the
powerpoint file would already be open. In this case, my script would
open it anew, and make the modifications in the newly opened file.
To prevent that problem, i need to be able to look at the filenames of
the open powerpoint files.
It there a way to do that ?


See if this might help (mutatis mutandis):

http://timgolden.me.uk/python/win32_how_do_i/see-if-an-excel-workbook-is-open.html

TJG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Type error: must be string or read-only character buffer, not seq

2011-04-19 Thread Peter Otten
Kann Vearasilp wrote:

> I tried concatenating string variables with multiple strings and have the
> file handle write the statement into a file. I don't know why I always get
> the type error: must be string or read-only character buffer, not seq
> error. I tried casting the whole new concatenated string using str(), but
> was not successful as well. Do you have any clue why this happen?

>  52 str(statement)
>  53 insert.write(statement)

Line 52 doesn't do what you think it does -- it converts statement to a 
string and then discards the result.

Try

statement = str(statement)
insert.write(statement)

or

insert.write(str(statement))

instead.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Metaclass confusion...

2011-04-19 Thread Peter Otten
Modulok wrote:

> List,
> 
> I've been messing with metaclasses. I thought I understood them until I
> ran into this. (See code below.) I was expecting the generated class,
> 'Foo' to have an 'x' class-level attribute, as forced upon it by the
> metaclass 'DracoMeta' at creation. Unfortunately, it doesn't and I don't
> know why. I'm obviously missing something big. I thought a metaclass
> created the class object, so this should work. (But obviously doesn't.)
> 
> 
> 
> class DracoMeta(type):
> '''Metaclass that creates a serial number as a class property.'''
> def __init__(self, name, bases, members):
> # Force a class attribute on the class-to-be:
> members['serial'] = 3
> 
> # Now make the class:
> type.__init__(self, name, bases, members)
> 
> class Foo(object):
> __metaclass__ = DracoMeta
> 
> print hasattr(Foo, 'serial')#<-- I was really expecting this to be
> True. 
> 
> I could add the attribute in the definition or a decorator, but the point
> was learning to use (albeit abuse) metaclasses. Anyway, if anyone could
> take a look I'd be grateful.

You are a little late to the show; the class, i. e. the instance of the 
metaclass with all its attributes has already been created by the 
type.__new__() method. If you move the manipulation of the members dict into 
a custom __new__() method you get the desired behaviour:

>>> class DracoMeta(type):
... def __new__(cls, name, bases, members):
... members["serial"] = 3
... return type.__new__(cls, name, bases, members)
...
>>> class Foo:
... __metaclass__ = DracoMeta
...
>>> Foo.serial
3

Alternatively you can take advantage of the fact that 'self' in the 
metaclass is the metaclass instance, i. e. the class, and assign directly to 
it:

>>> class NianMeta(type):
... def __init__(self, name, bases, members):
... self.serial = 3
...
>>> class Bar:
... __metaclass__ = NianMeta
...
>>> Bar.serial
3


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] win32com and python

2011-04-19 Thread Pierre Barthelemy
Hello,

I would need to control a powerpoint file from python. I have
installed the win32com library for python, then i used makepy to
create a powerpoint-specific library.

The things i need to do are pretty basic: open a file, create a new
slide, place a picture and a comment to the picture.

The problem i have is that, often, while the script is running, the
powerpoint file would already be open. In this case, my script would
open it anew, and make the modifications in the newly opened file.
To prevent that problem, i need to be able to look at the filenames of
the open powerpoint files.
It there a way to do that ?

And, by the way, is there any kind of help or manual or document to
understand how to use win32com and the related application-specific
libraries ?

The code i am using now is the following:
[code]
import win32com.client
import win32com.gen_py.ppt11b as ppt11b


ppt = win32com.client.Dispatch("Powerpoint.Application") #Open the
powerpoint application
ppt.Visible = True
pptfile = ppt.Presentations.Open('FileName',ReadOnly=0, Untitled=0,
WithWindow=1)#Open the desired ppt file

Slide = pptfile.Slides.Add(len(pptfile.Slides)+1, ppLayoutBlank)
shape1 = 
Slide.Shapes.AddTextbox(Orientation=0x1,Left=100,Top=50,Width=400,Height=100)
shape1.TextFrame.TextRange.Text='Trial'

shape2=Slide.Shapes.AddPicture(FileName='PictureName',
LinkToFile=False, SaveWithDocument=True, Left=100, Top=100, Width=400,
Height=400)
pptfile.Save()
pptfile.Close()
[\code]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding to PYTHONPATH

2011-04-19 Thread Steve Willoughby

On 19-Apr-11 06:49, mes...@juno.com wrote:

How can I add a directory to PYTHONPATH?  Using Ubuntu 10.04.


That's an environment variable, so it depends on your shell.  If 
PYTHONPATH already exists, you can add your directory to it (with colons 
between the names of directories).  But you probably want this to be a 
permanent change, so you need to edit the start-up file for your shell 
(.cshrc, .bashrc, .profile, whatever) and add an instruction to set that 
variable everytime you open a shell.

--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with strings in python3

2011-04-19 Thread Steve Willoughby

On 19-Apr-11 06:44, Rance Hall wrote:

On Mon, Apr 18, 2011 at 9:50 PM, Marc Tompkins  wrote:

On Mon, Apr 18, 2011 at 6:53 PM, Rance Hall  wrote:



I think you misunderstood me, I simply meant that the print "
".join(message) has to parse through each word in order to get any
output, I didn't mean to suggest that you got output one word at a
time.  Sorry for the confusion.


Not quite true.  join() doesn't need to parse through words or anything. 
 It takes a list of strings and efficiently copies them into a new 
large string.  Maybe you're thinking of split() or something?



I'm not sure I buy this explanation as strings have been used as keys
in dictionaries or "associative arrays" for a long time, a string
variable is variable or mutable, where a keyname can not be.


You're forgetting that you're not talking about a string VALUE like in 
most other languages, but rather a string OBJECT.  In C, if you store a 
value in a hash table with a string key, that key doesn't change even if 
the variable it came from takes a new value.  So it doesn't upset the 
key at all.


In Python, the string OBJECT you use may still be referenced by a 
variable, so if you were to mutate that string object, it would change 
and ALL variables referring to it would see the change, including the 
hash table structure which forms the dictionary.  In this sense, think 
of Python variable names more like C's pointers (sort of).  It's the 
same effect you'd get if you kept a pointer (in C) to the string value 
you stored your data in a hash table there, then went through that 
pointer to corrupt the hash table after the fact.


I'm not sure if your background in programming includes those concepts 
(I'm assuming so) or if I explained that clearly enough, but that 
illustrates why Python string OBJECTS need to be immutable (as are 
simple numeric OBJECTS.  The confusion that trips a lot of new Python 
programmers is that Python variables don't work like other languages, 
they're more of a blending of "variables", "pointers" and "references" 
which just "do the right thing" most of the time due to how Python 
manages variable access.  But they are not quite the same as any of 
those in other languages.


--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding to PYTHONPATH

2011-04-19 Thread Joel Goldstick
On Tue, Apr 19, 2011 at 9:49 AM, mes...@juno.com  wrote:

> How can I add a directory to PYTHONPATH?  Using Ubuntu 10.04.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

from the shell type this:

export PYTHONPATH=$PYTHONPATH:/your/path/to/python/modules




-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] adding to PYTHONPATH

2011-04-19 Thread mes...@juno.com
How can I add a directory to PYTHONPATH?  Using Ubuntu 10.04.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with strings in python3

2011-04-19 Thread Rance Hall
On Mon, Apr 18, 2011 at 9:50 PM, Marc Tompkins  wrote:
> On Mon, Apr 18, 2011 at 6:53 PM, Rance Hall  wrote:
>
>>
>> I'm going to go ahead and use this format even though it is deprecated
>> and then later when we upgrade it I can fix it.
>>
> And there you have your answer.
>
>> A list might make sense, but printing a message one word at a time
>> doesn't seem to me like much of a time saver.
>
>
> Did you try my example code?  It doesn't "print a message one word at a
> time"; any time you print " ".join(message), you get the whole thing.  Put a
> \n between the quotes, and you get the whole thing on separate lines.
>

I think you misunderstood me, I simply meant that the print "
".join(message) has to parse through each word in order to get any
output, I didn't mean to suggest that you got output one word at a
time.  Sorry for the confusion.

> It's just that it's not stored as a single string, but assembled on-demand.
> And you're right - doing this once or twice, or even ten times as in my
> example code, doesn't make a huge difference.  But at some point, if you
> intend to continue programming, you will run into a situation where your
> code needs to do something over and over and over and over... and getting
> out of bad habits like string concatenation can make a very noticeable
> difference in speed.
>
>>
>> But are CLI apps so rare that this sort of thing just doesn't happen
>> anymore?
>
> No, they're not all that rare, and CLI-ness has nothing to do with it.
>
>>
>> This seems like such a basic thing and deprecating it seems
>> rather harsh.
>>
> Bottom line: Python is not BASIC.  In BASIC, strings aren't immutable, so
> in-place string concatenation doesn't carry (much of) a performance
> penalty.  In Python, it will make your program unnecessarily slow.  I think
> you're under the impression that "deprecation" is a value judgment, or that
> "message = message + foo" is deprecated because it looks like BASIC syntax.
> Neither is true.
>

Again a little misunderstanding.  I didn't mean BASIC the programming
language.  I forgot all I knew about that language long ago.  I mean
basic in the fundamental concept sense.

Variables are variable, that's why we call them variable.
Constants are constant, and that's why we call them constant.

The idea of immutable strings variables blurs the line between these
two mathematical concepts which are part of my thinking about teaching
math (which I do at a local community college) as well as my thinking
of computer programming.

> From the Python wiki:
> http://wiki.python.org/moin/PythonSpeed/PerformanceTips#String_Concatenation
>

Thanks for this pointer, it was interesting reading.

> We may ask ourselves "why did Guido decide to make strings immutable in the
> first place?"; probably the best reason is "so that strings can be used as
> keys in a dictionary", but since I'm not Guido - not even Dutch! - I really
> can't speak for him.
>

I'm not sure I buy this explanation as strings have been used as keys
in dictionaries or "associative arrays" for a long time, a string
variable is variable or mutable, where a keyname can not be.

Anyway, thanks everyone for taking the time to help me get my head
wrapped around this, I'm not sure I managed to do it yet, but the
seeds were planted.

Rance
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Metaclass confusion...

2011-04-19 Thread Modulok
List,

I've been messing with metaclasses. I thought I understood them until I ran
into this. (See code below.) I was expecting the generated class, 'Foo' to have
an 'x' class-level attribute, as forced upon it by the metaclass 'DracoMeta'
at creation. Unfortunately, it doesn't and I don't know why. I'm obviously
missing something big. I thought a metaclass created the class object,
so this should work. (But obviously doesn't.)



class DracoMeta(type):
'''Metaclass that creates a serial number as a class property.'''
def __init__(self, name, bases, members):
# Force a class attribute on the class-to-be:
members['serial'] = 3

# Now make the class:
type.__init__(self, name, bases, members)

class Foo(object):
__metaclass__ = DracoMeta

print hasattr(Foo, 'serial')#<-- I was really expecting this to be True.


I could add the attribute in the definition or a decorator, but the point was
learning to use (albeit abuse) metaclasses. Anyway, if anyone could take
a look I'd be grateful.

Thanks!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Type error: must be string or read-only character buffer, not seq

2011-04-19 Thread Luke Paireepinart
It's saying one of your variables is not a string. Is one of them a sequence? 
Perhaps Mir-seq? If so, you need to come up with a way to build a string from 
this object. You can call the str method and pass in your object or you can 
explicitly create a string from the data in the object.

-
Sent from a mobile device. Apologies for brevity and top-posting.
-

On Apr 19, 2011, at 7:57 AM, Kann Vearasilp  wrote:

> Dear all,
> 
> I tried concatenating string variables with multiple strings and have the 
> file handle write the statement into a file. I don't know why I always get 
> the type error: must be string or read-only character buffer, not seq error. 
> I tried casting the whole new concatenated string using str(), but was not 
> successful as well. Do you have any clue why this happen?
> 
> Best,
> 
> Kann
> 
> 
> #
>  42 
>  43 statement = 'mirna = miRBase(accession = "' + mir_acc + '", '\
>  44 + 'name = "' + mir_name + '", '\
>  45 + 'specie = "' + mir_specie + '", '\
>  46 + 'description = "' + mir_desc + '", '\
>  47 + 'refDBs = "' + mir_dbrefs + '", '\
>  48 + 'comment = "' + mir_comment + '", '\
>  49 + 'seq = "' + mir_seq + '")' + "\n"
>  50 
>  51 
>  52 str(statement)
>  53 insert.write(statement)
> 
> 3
> processing the insert statment
> Traceback (most recent call last):
>   File "mirbase.py", line 60, in 
> generate_insert(db_file)
>   File "mirbase.py", line 53, in generate_insert
> insert.write(statement)
> TypeError: must be string or read-only character buffer, not Seq
> #
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Type error: must be string or read-only character buffer, not seq

2011-04-19 Thread Kann Vearasilp
Dear all,

I tried concatenating string variables with multiple strings and have the
file handle write the statement into a file. I don't know why I always get
the type error: must be string or read-only character buffer, not seq error.
I tried casting the whole new concatenated string using str(), but was not
successful as well. Do you have any clue why this happen?

Best,

Kann


#
 42
 43 statement = 'mirna = miRBase(accession = "' + mir_acc + '", '\
 44 + 'name = "' + mir_name + '", '\
 45 + 'specie = "' + mir_specie + '", '\
 46 + 'description = "' + mir_desc + '", '\
 47 + 'refDBs = "' + mir_dbrefs + '", '\
 48 + 'comment = "' + mir_comment + '", '\
 49 + 'seq = "' + mir_seq + '")' + "\n"
 50
 51
 52 str(statement)
 53 insert.write(statement)

3
processing the insert statment
Traceback (most recent call last):
  File "mirbase.py", line 60, in 
generate_insert(db_file)
  File "mirbase.py", line 53, in generate_insert
insert.write(statement)
TypeError: must be string or read-only character buffer, not Seq
#
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with strings in python3

2011-04-19 Thread Steven D'Aprano

Rance Hall wrote:

Ok so I know what I am doing is deprecated (or at least poor form) but
the replacement must be awkward cause I'm not getting it.

[...]

message = "Bah."
if test:
   message = message + " Humbug!"



It's not deprecated, nor is it poor form. However, it can be abused, or 
perhaps *misused* is a better term, and it is the misuse you need to 
watch out for.


Somebody posted a similar comment on another Python list today, which I 
answered, so I'll copy and paste my answer here:



There's nothing wrong with concatenating (say) two or three strings.
What's a bad idea is something like:

s = ''
while condition:
s += "append stuff to end"

Even worse:

s = ''
while condition:
s = "insert stuff at beginning" + s

because that defeats the runtime optimization (CPython only!) that
*sometimes* can alleviate the badness of repeated string concatenation.

See Joel on Software for more:

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

But a single concatenation is more or less equally efficient as string
formatting operations (and probably more efficient, because you don't
have the overheard of parsing the format mini-language).

For repeated concatenation, the usual idiom is to collect all the
substrings in a list, then join them all at once at the end:

pieces = []
while condition:
pieces.append('append stuff at end')
s = ''.join(pieces)




--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor