Re: [Tutor] Really miss the C preprocessor!!

2010-03-05 Thread Steven D'Aprano
On Sat, 6 Mar 2010 04:13:49 pm Gil Cosson wrote:
> I have some code to perform an exponential backoff. I am interacting
> with a few different web services. Checking for a specific Exception
> and then re-invoking the failed call after waiting a bit. I don't
> want to  code the backoff in ten different places. Really miss the C
> pre-processor.
>
> I am tempted to try something like the following, but I understand
> that eval should be a last resort.
>
> Any pythonic best practice for this situation?:

Functions are first-class objects that can be passed around as data. Use 
them.

def check_some_website(url, x):
# whatever


def exponential_backoff(function, args, exception, numretries):
# Backoff 1 second, 2 seconds, 4 seconds, 8, 16, ...
t = 1
for i in xrange(numretries):
try:
return function(*args)
except exception:
time.sleep(t)
t *= 2
raise exception("no connection after %d attempts" % numretries)


result = exponential_backoff(check_some_website, 
("http://example.com";, 42), HTTPError, 8)


Any time you think you need eval, you almost certainly don't.



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


[Tutor] Really miss the C preprocessor!!

2010-03-05 Thread Gil Cosson

I have some code to perform an exponential backoff. I am interacting with a few 
different web services. Checking for a specific Exception and then re-invoking 
the failed call after waiting a bit. I don't want to  code the backoff in ten 
different places. Really miss the C pre-processor.

I am tempted to try something like the following, but I understand that eval 
should be a last resort.

Any pythonic best practice for this situation?:

from  time import sleep
from random import randint

def exponentialbackoff(exception,numretrys,somecode):
    currentIteration=0
    SuccessfulCall=False
    rc=None
    globalnamespace=getglobals(,globals)
    while currentiteration___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Instantiating a list of strings into a list of classes

2010-03-05 Thread Benno Lang
On 6 March 2010 10:38, Daryl V  wrote:
> I have a csv list of data, of the form:
> plot, utmN83_X, utmN83_Y, plot_radius_m
> Spring1,348545,3589235,13.2
> etc.
> I built a nifty ClassGPSPoint(Xpos,Ypos,plotRadius,workPaths) that eats the
> X&Y positions, the plot radius, and previously instantiated object holding
> all of the appropriate paths definitions to access the LiDAR LAS files.
> I make a nice CSV reader with one line (did I mention I LOVE python?)...
> plotReader =
> csv.reader(open("N:\\GIS_Projects\\095_ForestMetrics\\7_Analyses\\FinalCylinders\\Plots.csv"))
> What I want to do is use the first entry in that row (row[0]) as the
> variable name for the instantiated class.  I'd get an instantiated GPSPoint
> object called 'Spring1' that would yield all my methods and defined values
> (Spring1.pathLASfile, Spring1.perturbXY(), etc)
> Hence, in pseudocode:
> for row in plotReader:
>    row[0] = GPSPoint(row[1],row[2],18.3,workPaths)

All you're doing here is replacing the name stored in row[0] with the
new GPSPoint object.

If I read your description correctly, I think what you're looking for
should behave like this:
# row read from CSV (I assume CSV values are always read as strings)
row = ['Spring1', '348545', '3589235', '13.2']
# what the code you want should do automatically
Spring1 = GPSPoint('348545','3589235','13.2', workPaths)

I don't know how to do that in Python - at a guess it would look
something like (pseudocode):
__module__.vars[row[0]] = GPSPoint(...)
Someone else probably knows how to do that, but I have a fairly strong
feeling that it's the wrong approach to your problem.
When you write your CSV file, each GPSPoint needs to know what its
variable name is, which doesn't seem to make a whole lot of sense. If
you have a set number of objects, then maybe you should just read and
write them in a known order - your program can call them anything it
likes; it won't affect the storage and loading of the data.
Alternatively, if for some reason you really want to associate a name
with each GPSPoint, I would suggest storing the points in a
dictionary, e.g.
points = {}
for row in plotReader:
points[row[0]] = GPSPoint(row[1], row[2], row[3], workPaths)

Then when you need to write to a CSV, the name to go in the first
column is simply the key of that dictionary item.

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


Re: [Tutor] Encoding

2010-03-05 Thread Mark Tolonen


"Giorgio"  wrote in message 
news:23ce85921003050915p1a084c0co73d973282d8fb...@mail.gmail.com...

2010/3/5 Dave Angel 

I think the problem is that i can't find any difference between 2 lines
quoted above:

a = u"ciao è ciao"

and

a = "ciao è ciao"
a = unicode(a)


Maybe this will help:

   # coding: utf-8

   a = "ciao è ciao"
   b = u"ciao è ciao".encode('latin-1')

a is a UTF-8 string, due to #coding line in source.
b is a latin-1 string, due to explicit encoding.

   a = unicode(a)
   b = unicode(b)

Now what will happen?  unicode() uses 'ascii' if not specified, because it 
has no idea of the encoding of a or b.  Only the programmer knows.  It does 
not use the #coding line to decide.


#coding is *only* used to specify the encoding the source file is saved in, 
so when Python executes the script, reads the source and parses a literal 
Unicode string (u'...', u"...", etc.) the bytes read from the file are 
decoded using the #coding specified.


If Python parses a byte string ('...', "...", etc.) the bytes read from the 
file are stored directly in the string.  The coding line isn't even used. 
The bytes will be exactly what was saved in the file between the quotes.


-Mark


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


[Tutor] Instantiating a list of strings into a list of classes

2010-03-05 Thread Daryl V
Hello All-

I cut my teeth of Fortran95, and in the distant past rode the turtle, and
while I enjoy the mind-bendy feeling of shifting my programming paradigm
(and LOVE LOVE LOVE Python), I get sheepish when I feel I'm missing
something basic.

So:
I have a csv list of data, of the form:
plot, utmN83_X, utmN83_Y, plot_radius_m
Spring1,348545,3589235,13.2
etc.

I built a nifty ClassGPSPoint(Xpos,Ypos,plotRadius,workPaths) that eats the
X&Y positions, the plot radius, and previously instantiated object holding
all of the appropriate paths definitions to access the LiDAR LAS files.

I make a nice CSV reader with one line (did I mention I LOVE python?)...

plotReader =
csv.reader(open("N:\\GIS_Projects\\095_ForestMetrics\\7_Analyses\\FinalCylinders\\Plots.csv"))

What I want to do is use the first entry in that row (row[0]) as the
variable name for the instantiated class.  I'd get an instantiated GPSPoint
object called 'Spring1' that would yield all my methods and defined values
(Spring1.pathLASfile, Spring1.perturbXY(), etc)
Hence, in pseudocode:

for row in plotReader:
   row[0] = GPSPoint(row[1],row[2],18.3,workPaths)

But that doesn't work.  I'm probably missing something basic and profound,
(I was trying to use global to track my paths until I got my mind around the
passing the instantiated object thing, but whaddya gonna do?  Sequential to
OO is a big shift, you know?)

Thanks ya'll -

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


Re: [Tutor] Process list elements as consecutive pairs

2010-03-05 Thread Hugo Arts
2010/3/5 Emad Nawfal (عمـ نوفل ـاد) :
>
>
> Here is a general solution that I also took from the Tutor list some time
> ago. It allows you to have consequences of (any) length.
>
 def makeVectors(length, listname):
> ...     """takes the length of the vector and a listname returns vectors"""
> ...     vectors = (listname[i:i+length] for i in
> range(len(listname)-length+1))
> ...     return vectors
> ...
 myList = [1,2,3,4,5,6]
>
 bigrams = makeVectors(2, myList)
 bigrams
>  at 0xb7227e64>
 for bigram in bigrams: print bigram
> ...
> [1, 2]
> [2, 3]
> [3, 4]
> [4, 5]
> [5, 6]

Except the OP requested pairs (1, 2), (3, 4), i.e. with no duplicate
elements. Here is a generator that does what you need:

def pairs(seq):
it = iter(seq)
try:
while True:
yield it.next(), it.next()
except StopIteration:
return

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


Re: [Tutor] My tutorial

2010-03-05 Thread Alan Gauld

It's back.

Enjoy

Alan Gauld
Author of the Learn To Program website
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] Encoding

2010-03-05 Thread Dave Angel

Giorgio wrote:

2010/3/5 Dave Angel 
  

In other words, you don't understand my paragraph above.




Maybe. But please don't be angry. I'm here to learn, and as i've run into a
very difficult concept I want to fully undestand it.


  
I'm not angry, and I'm sorry if I seemed angry.  Tone of voice is hard 
to convey in a text message.

Once the string is stored in t as an 8 bit string, it's irrelevant what the
source file encoding was.




Ok, you've said this 2 times, but, please, can you tell me why? I think
that's the key passage to understand how encoding of strings works. The
source file encoding affects all file lines, also strings.

Nope, not strings.  It only affects string literals.

 If my encoding is
UTF8 python will read the string "ciao è ciao" as 'ciao \xc3\xa8 ciao' but
if it's latin1 it will read 'ciao \xe8 ciao'. So, how can it be irrelevant?

I think the problem is that i can't find any difference between 2 lines
quoted above:

s = u"ciao è ciao"

and

t = "ciao è ciao"
c = unicode(t)

[**  I took the liberty of making the variable names different so I can refer 
to them **]
  
I'm still not sure whether your confusion is to what the rules are, or 
why the rules were made that way.  The rules are that an unqualified 
conversion, such as the unicode() function with no second argument, uses 
the default encoding, in strict mode.  Thus the error.


Quoting the help: 
"If no optional parameters are given, unicode() will mimic the behaviour 
of str() except that it returns Unicode strings instead of 8-bit 
strings. More precisely, if /object/ is a Unicode string or subclass it 
will return that Unicode string without any additional decoding applied.


For objects which provide a __unicode__() 
<../reference/datamodel.html#object.__unicode__> method, it will call 
this method without arguments to create a Unicode string. For all other 
objects, the 8-bit string version or representation is requested and 
then converted to a Unicode string using the codec for the default 
encoding in 'strict' mode.

"

As for why the rules are that, I'd have to ask you what you'd prefer.  
The unicode() function has no idea that t was created from a literal 
(and no idea what source file that literal was in), so it has to pick 
some coding, called the default coding.  The designers decided to use a 
default encoding of ASCII, because manipulating ASCII strings is always 
safe, while many functions won't behave as expected when given UTF-8 
encoded strings.  For example, what's the 7th character of t ?  That is 
not necessarily the same as the 7th character of s, since one or more of 
the characters in between might have taken up multiple bytes in s.  That 
doesn't happen to be the case for your accented character, but would be 
for some other European symbols, and certainly for other languages as well.

If you then (whether it's in the next line, or ten thousand calls later)
try to convert to unicode without specifying a decoder, it uses the default
encoder, which is a application wide thing, and not a source file thing.  To
see what it is on your system, use sys.getdefaultencoding().




And this is ok. Spir said that it uses ASCII, you now say that it uses the
default encoder. I think that ASCII on spir's system is the default encoder
so.


  
I don't know, but I think it's the default in every country, at least on 
version 2.6.  It might make sense to get some value from the OS that 
defined the locally preferred encoding, but then a program that worked 
fine in one locale might fail miserably in another.

The point is that there isn't just one global value, and it's a good thing.
 You should figure everywhere characters come into  your program (eg. source
files, raw_input, file i/o...) and everywhere characters go out of your
program, and deal with each of them individually.




Ok. But it always happen this way. I hardly ever have to work with strings
defined in the file.

  
Not sure what you mean by "the file."  If you mean the source file, 
that's what your examples are about.   If you mean a data file, that's 
dealt with differently.
  

Don't store anything internally as strings, and you won't create the
ambiguity you have with your 't' variable above.

DaveA




Thankyou Dave

Giorgio



  


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


Re: [Tutor] Process list elements as consecutive pairs

2010-03-05 Thread عمـ نوفل ـاد
On Fri, Mar 5, 2010 at 1:03 PM, Wayne Werner  wrote:

> On Fri, Mar 5, 2010 at 11:56 AM, Rüdiger Wolf <
> rudiger.w...@throughputfocus.com> wrote:
>
>> Hi
>>
>> I am trying to Process list elements as consecutive pairs  into
>> consecutive pairs.
>> Any pythonic suggestions?
>>
>> listin = [1,2,3,4,5,6,7,8,9,10]
>> I want to process as consecutive pairs
>> 1,2
>> 3,4
>> 5,6
>> 7,8
>> 9,10
>>
>
> for x in xrange(0, len(listin), 2):
> print listin[x], listin[x+1]
>
> - that's probably how I'd do it anyway.
>
> HTH,
> Wayne
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> Here is a general solution that I also took from the Tutor list some time
ago. It allows you to have consequences of (any) length.

>>> def makeVectors(length, listname):
... """takes the length of the vector and a listname returns vectors"""
... vectors = (listname[i:i+length] for i in
range(len(listname)-length+1))
... return vectors
...
>>> myList = [1,2,3,4,5,6]

>>> bigrams = makeVectors(2, myList)
>>> bigrams
 at 0xb7227e64>
>>> for bigram in bigrams: print bigram
...
[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
>>>


-- 
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد
الغزالي
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington

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


Re: [Tutor] Process list elements as consecutive pairs

2010-03-05 Thread Wayne Werner
On Fri, Mar 5, 2010 at 11:56 AM, Rüdiger Wolf <
rudiger.w...@throughputfocus.com> wrote:

> Hi
>
> I am trying to Process list elements as consecutive pairs  into
> consecutive pairs.
> Any pythonic suggestions?
>
> listin = [1,2,3,4,5,6,7,8,9,10]
> I want to process as consecutive pairs
> 1,2
> 3,4
> 5,6
> 7,8
> 9,10
>

for x in xrange(0, len(listin), 2):
print listin[x], listin[x+1]

- that's probably how I'd do it anyway.

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


Re: [Tutor] Process list elements as consecutive pairs

2010-03-05 Thread greg whittier
On Fri, Mar 5, 2010 at 12:56 PM, Rüdiger Wolf <
rudiger.w...@throughputfocus.com> wrote:

> I am trying to Process list elements as consecutive pairs  into
> consecutive pairs.
> Any pythonic suggestions?
>
> listin = [1,2,3,4,5,6,7,8,9,10]
> I want to process as consecutive pairs
> 1,2
> 3,4
> 5,6
> 7,8
> 9,10
>

Not sure it's pythonic but

zip(listin[0::2],listin[1::2])
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Process list elements as consecutive pairs

2010-03-05 Thread Rüdiger Wolf
Hi

I am trying to Process list elements as consecutive pairs  into
consecutive pairs.  
Any pythonic suggestions?

listin = [1,2,3,4,5,6,7,8,9,10]
I want to process as consecutive pairs
1,2
3,4
5,6
7,8
9,10

Thanks
Rudiger

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


Re: [Tutor] Bowing out

2010-03-05 Thread Dave Kuhlman
On Wed, Mar 03, 2010 at 08:17:45AM -0500, Kent Johnson wrote:
> Hi all,
> 
> After six years of tutor posts my interest and energy have waned and
> I'm ready to move on to something new. I'm planning to stop reading
> and contributing to the list. I have handed over list moderation
> duties to Alan Gauld and Wesley Chun.
> 
> Thanks to everyone who contributes questions and answers. I learned a
> lot from my participation here.
> 
> So long and keep coding!

Thank you Kent, for all you've done for those who came to this list
for help.

I admire your ability and knowledge about Python.  And, I
appreciate the huge amount of effort you've put into helping us.

- Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] import simplejson got Floating exception on RedHat

2010-03-05 Thread Ming Xue

Hi Tutors,

I installed simplejson-2.0.9 for Python 2.5 using `setup.py install` on RedHad 
machine. The installation went through without any error and it created an egg 
(site-packages/simplejson-2.0.9-py2.5-linux-x86_64.egg). However when I tested 
in a python shell by import simplejson, I got Floating exception and python 
shell quit. Any ideas of what could be wrong?

Thanks,
Ming  


  
_
Hotmail: Trusted email with powerful SPAM protection.
http://clk.atdmt.com/GBL/go/201469227/direct/01/___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encoding

2010-03-05 Thread Giorgio
2010/3/5 Dave Angel 
>
> In other words, you don't understand my paragraph above.


Maybe. But please don't be angry. I'm here to learn, and as i've run into a
very difficult concept I want to fully undestand it.


> Once the string is stored in t as an 8 bit string, it's irrelevant what the
> source file encoding was.


Ok, you've said this 2 times, but, please, can you tell me why? I think
that's the key passage to understand how encoding of strings works. The
source file encoding affects all file lines, also strings. If my encoding is
UTF8 python will read the string "ciao è ciao" as 'ciao \xc3\xa8 ciao' but
if it's latin1 it will read 'ciao \xe8 ciao'. So, how can it be irrelevant?

I think the problem is that i can't find any difference between 2 lines
quoted above:

a = u"ciao è ciao"

and

a = "ciao è ciao"
a = unicode(a)


> If you then (whether it's in the next line, or ten thousand calls later)
> try to convert to unicode without specifying a decoder, it uses the default
> encoder, which is a application wide thing, and not a source file thing.  To
> see what it is on your system, use sys.getdefaultencoding().
>

And this is ok. Spir said that it uses ASCII, you now say that it uses the
default encoder. I think that ASCII on spir's system is the default encoder
so.


> The point is that there isn't just one global value, and it's a good thing.
>  You should figure everywhere characters come into  your program (eg. source
> files, raw_input, file i/o...) and everywhere characters go out of your
> program, and deal with each of them individually.


Ok. But it always happen this way. I hardly ever have to work with strings
defined in the file.


> Don't store anything internally as strings, and you won't create the
> ambiguity you have with your 't' variable above.
>
> DaveA
>

Thankyou Dave

Giorgio



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


Re: [Tutor] Encoding

2010-03-05 Thread Dave Angel

Giorgio wrote:


Ok,so you confirm that:

s = u"ciao è ciao" will use the file specified encoding, and that

t = "ciao è ciao"
t = unicode(t)

Will use, if not specified in the function, ASCII. It will ignore the
encoding I specified on the top of the file. right?



  

A literal  "u" string, and only such a (unicode) literal string, is
affected by the encoding specification.  Once some bytes have been stored in
a 8 bit string, the system does *not* keep track of where they came from,
and any conversions then (even if they're on an adjacent line) will use the
default decoder.  This is a logical example of what somebody said earlier on
the thread -- decode any data to unicode as early as possible, and deal only
with unicode strings in the program.  Then, if necessary, encode them into
whatever output form immediately before (or while) outputting them.





 Ok Dave, What i don't understand is why:

s = u"ciao è ciao" is converting a string to unicode, decoding it from the
specified encoding but

t = "ciao è ciao"
t = unicode(t)

That should do exactly the same instead of using the specified encoding
always assume that if i'm not telling the function what the encoding is, i'm
using ASCII.

Is this a bug?

Giorgio
  
In other words, you don't understand my paragraph above.  Once the 
string is stored in t as an 8 bit string, it's irrelevant what the 
source file encoding was.  If you then (whether it's in the next line, 
or ten thousand calls later) try to convert to unicode without 
specifying a decoder, it uses the default encoder, which is a 
application wide thing, and not a source file thing.  To see what it is 
on your system, use sys.getdefaultencoding().


There's an encoding specified or implied for each source file of an 
application, and they need not be the same.  It affects string literals 
that come from that particular file. It does not affect any other 
conversions, as far as I know.  For that matter, many of those source 
files may not even exist any more by the time the application is run.


There are also encodings attached to each file object, I believe, though 
I've got no experience with that.  So sys.stdout would have an encoding 
defined, and any unicode strings passed to it would be converted using 
that specification.


The point is that there isn't just one global value, and it's a good 
thing.  You should figure everywhere characters come into  your program 
(eg. source files, raw_input, file i/o...) and everywhere characters go 
out of your program, and deal with each of them individually.  Don't 
store anything internally as strings, and you won't create the ambiguity 
you have with your 't' variable above.


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


Re: [Tutor] object representation

2010-03-05 Thread Lie Ryan
On 03/05/2010 12:45 PM, Steven D'Aprano wrote:
> E.g. a trie needs six pointers just to represent the single 
> key "python":
> 
> '' -> 'p' -> 'y' -> 't' -> 'h' -> 'o' -> 'n'
> 
> while a hash table uses just one:
> 
> -> 'python'

You can argue that had trie beed used as the datatype, there will
actually be no need to store the key's string representation; the index
of the object in the trie implies the textual representation. Such that,
you will still need 6 pointers, but you won't need to store a string
object. It will just be:

'' -> ptrP -> ptrY -> ptrT -> ptrH -> ptrO -> ptrN

and if for some reason the name is needed (perhaps for debugging?); then
there could be an algorithm to reverse-map the ptrXs to char. I can
imagine that to be implementable if variable names in python be limited
to alphanumerics only and probably a select few of symbols. Unicode
names makes things difficult though...

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


Re: [Tutor] Understanding (Complex) Modules

2010-03-05 Thread bob gailer

Clarifications:

A module is a file. It may or may not contain python code. If it does 
not an exception will be raised when importing.


Import executes the module's code exactly the same as if the module had 
been run as a script (main program).


References to module objects are stored in a dict (sys.modules)s. You 
will notice many modules that have been "pre-imported":


>>> import sys
>>> for x in sys.modules.keys(): print x
...
'copy_reg'
'sre_compile'
'locale'
'_sre'
'functools'
'encodings'
'site'
'__builtin__'
'operator'
'__main__'
'types'
'encodings.encodings'
'abc'
'encodings.cp437'
'errno'
'encodings.codecs'
'sre_constants'
're'
'_abcoll'
'ntpath'
'_codecs'
'nt'
'_warnings'
'genericpath'
'stat'
'zipimport'
'encodings.__builtin__'
'warnings'
'UserDict'
'encodings.cp1252'
'sys'
'codecs'
'os.path'
'_functools'
'_locale'
'signal'
'linecache'
'encodings.aliases'
'exceptions'
'sre_parse'
'os'
>>>

So all import sys does is:
  sys = sys.modules['sys']

Whereas import foo (assuming we refer to foo.py):
  if 'foo' in sys.modules:
foo = sys.modules['foo']
  else:
compile foo.py
if successful:
  execute the compiled code thus creating a module object
  if successful:
sys.modules['foo'] = the new module object
foo = sys.modules['foo']
Herelin lies a gotcha:
  import foo again does NOT recompile; it just reassigns foo = 
sys.modules['foo'].

  reload(foo) will go thru the compile execute assign sequence again.

Notice __main__ - that is the module of the main program.
>>> sys.modules['__main__']

>>> dir(sys.modules['__main__'])
['__builtins__', '__doc__', '__name__', '__package__', 'sys', 'x']
>>>

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Encoding

2010-03-05 Thread Giorgio
>
>
>> Ok,so you confirm that:
>>
>> s = u"ciao è ciao" will use the file specified encoding, and that
>>
>> t = "ciao è ciao"
>> t = unicode(t)
>>
>> Will use, if not specified in the function, ASCII. It will ignore the
>> encoding I specified on the top of the file. right?
>>
>>
>>
> A literal  "u" string, and only such a (unicode) literal string, is
> affected by the encoding specification.  Once some bytes have been stored in
> a 8 bit string, the system does *not* keep track of where they came from,
> and any conversions then (even if they're on an adjacent line) will use the
> default decoder.  This is a logical example of what somebody said earlier on
> the thread -- decode any data to unicode as early as possible, and deal only
> with unicode strings in the program.  Then, if necessary, encode them into
> whatever output form immediately before (or while) outputting them.
>
>
>
 Ok Dave, What i don't understand is why:

s = u"ciao è ciao" is converting a string to unicode, decoding it from the
specified encoding but

t = "ciao è ciao"
t = unicode(t)

That should do exactly the same instead of using the specified encoding
always assume that if i'm not telling the function what the encoding is, i'm
using ASCII.

Is this a bug?

Giorgio
-- 
--
AnotherNetFellow
Email: anothernetfel...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Collaborative Comp Sci education using Python

2010-03-05 Thread Serdar Tumgoren
Hey everyone,
A while back some folks said they were organizing an online study group to
work through Wesley Chun's Core Python. I just stumbled into another online
study group that might also be of interest:

http://www.crunchcourse.com/class/mit-opencourseware-600-introduction/2010/jan/

The study group is built around MIT's OpenCourseware's Into to CompSci and
Programming, which uses Python as its instructional language.

http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2008/CourseHome/index.htm

I'd be interested in hearing of similar Python-based study groups out there,
so shout out if you know of any.

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


[Tutor] My tutorial

2010-03-05 Thread ALAN GAULD
Apologies to any users of my tutorial who can't access it

I am a victim of my own success and have bust the bandwidth 
limit on the web site for the month. I will need to upgrade 
my subscription package...

Until then, apologies once more.
The old V2 freenet site seems to still be available if you 
are stuck...

http://www.freenetpages.co.uk/hp/alan.gauld/

 Alan Gauld
Author of the Learn To Program website
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] How to wrap ctype functions

2010-03-05 Thread Mark Tolonen


"Jan Jansen"  wrote in message 
news:f17500b71003030943w606925edie41b41d6d64ef...@mail.gmail.com...

Hi there,

I wonder what's the best way to wrap given function calls (in this case
ctype function calls but more generally built-in functions and those 
kinds).

I have a huge c library and almost all functions return an error code. The
library also contains a function, that returns the corresponding error
message to the error code. So, what I need to do for every call to one of
the libraries functions looks like this:

error_code = my_c_library.SOME_FUNCTION_
CALL(argument)
if error_code != 0:
  error_message = my_c_library.GET_ERROR_TEXT(error_code)
  print "error in function call SOME_FUNCTION_CALL"
  print error_message
  my_c_library.EXIT_AND_CLEAN_UP()


ctypes has a couple of methods to post process return values.

1.  A callable can be assigned has the .restype attribute of the function 
object.  In this case, the function is assumed to return an integer, and it 
is passed to the callable.  The function could raise an exception for 
non-zero return values.  This usage is deprecated.  See "16.15.1.8. Return 
types" in the Python docs (http://docs.python.org/library/ctypes.html).


2.  Any return type can be assigned to .restype, and a callable can be 
assigned to the .errcheck attribute.  This has more flexibility than #1 
since it works for return types without int.  The callable is provided the 
return value, original function object, and original arguments to help 
customize the behavior of the return value.  See "16.15.2.3. Foreign 
functions" in the docs.




Also, for some function calls I would need to do some preperations like:

error_code = my_c_library.LOG_IN_AS_ADMINISTRATOR(admin_user,
admin_password)
error_code = my_c_library.SOME_FUNCTION_CALL(argument)

I like the decorator idea, but I can't figure out if it's applicable here.
To be able to call the function in a manner like this would be great, e.g.

@change_user(admin_user, admin_password)
@error_handling
my_c_library.SOME_FUNCTION_CALL(argument)


Decorators don't decorate calls to functions, just function declarations. 
Here's a *rough* example:



def prep(func):

...   def prepwork(*args,**kwargs):
...  print 'doing prep work...'
...  func(*args,**kwargs)
...   return prepwork
...

@prep

... def something(a,b):
...   print a,b
...

something(1,2)

doing prep work...
1 2

-Mark


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


Re: [Tutor] object representation

2010-03-05 Thread Dave Angel

spir wrote:

On Thu, 04 Mar 2010 09:22:52 -0500
Dave Angel  wrote:

  
Still, slots are important, because I suspect 
that's how built-ins are structured, to make the objects so small.



Sure, one cannot alter their structure. Not even of a direct instance of 
:
  

o = object()
o.n=1


Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'object' object has no attribute 'n'

  
Now, some objects, probably most of the built-ins, are not extensible.  
You can't add new methods, or alter the behavior much.



This applies to any attr, not only methods, also plain "information":
  

s = "abc"
s.n=1


Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'str' object has no attribute 'n'


  
Other objects, 
such as instances of a class you write, are totally and very flexible.



conceptually this is equivalent to have no __slots__ slot. Or mayby they could 
be implemented using structs (which values would be pointers), instead of 
dicts. A struct is like a fixed record, as opposed to a dict. What do you 
think? On the implementation side, this would be much simpler, lighter, and 
more efficient.
Oh, this gives me an idea... (to implement so-called "value objects").

Denis
  
having not played much with slots, my model is quite weak there.  But I 
figure the dictionary is in the implementation structure, along with a 
flag saying that it's readonly.  Each item of such a dictionary would be 
an index into the fixed table in the object.  Like a struct, as you say, 
except that in C, there's no need to know the names of the fields at run 
time.


DaveA

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