Re: [Tutor] updating step size while in loop

2012-07-09 Thread Wayne Werner

While you can't do it with a straight generator, you can create your own:

class MyIter:
def __init__(self, start, stop, step=1):
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
self.cur = self.start
while self.cur < self.stop:
yield self.cur
self.cur += 1

And then you could do the following:
In [36]: i = MyIter(1, 10)

In [37]: for x in i:
   : if x % 2:
   : i.cur += 1
   : print(x)
   :
1
3
5
7
9

-HTH,
Wayne

On Tue, 10 Jul 2012, Hugo Arts wrote:


On Mon, Jul 9, 2012 at 11:59 PM, Abhishek Pratap 
wrote:
  hey guys

  I want to know whether it is possible for dynamically update the
  step
  size in xrange  or someother slick way.

  Here is what I am trying to do, if during a loop I find the x in
  list
  I want to skip next #n iterations.


  for x in xrange(start,stop,step):
      if x in list:
           step = 14
      else:
           step = 1



  Thanks!
  -Abhi


It is not possible with a range object. You'll have to make a while loop and
keep track of the step yourself.

Hugo

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


Re: [Tutor] confusion about imports

2012-07-09 Thread Steven D'Aprano

Mark Lawrence wrote:

On 09/07/2012 16:56, Chris Hare wrote:


So, I have to admit, imports have me really confused.  I am trying to 
break apart a 10,000+ line single file into various files


Please don't break the file up for the sake of doing it, you're writing 
python not java :-)


Agreed, but 10,000 lines is a pretty good reason for breaking up a file.

The largest single module in the Python standard library is decimal.py, and 
that's only 6250 lines. With 18 classes and 20 top-level functions, to my 
mind, that's about the limit of maintainability for a single file.



--
Steven

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


Re: [Tutor] confusion about imports

2012-07-09 Thread Chris Hare
Good advice - thanks for that.  And I think you're right - I think what is 
happening is in fact a bunch of circular references.  As I resolve issues, I 
will be looking for those!  Appreciate all the advice!

On Jul 9, 2012, at 5:16 PM, Dave Angel wrote:

> On 07/09/2012 11:56 AM, Chris Hare wrote:
>> So, I have to admit, imports have me really confused.  I am trying to break 
>> apart a 10,000+ line single file into various files, one for each class, and 
>> one containing a whole bunch of functions which are used by a lot of 
>> classes.  Some of those functions use calls to methods in a Class.  Even 
>> though the Class has been imported, I get a nameError where trying to use 
>> the class.  I have read about Classes and packages and modules, but import 
>> just has me confused.
> Something I haven't seen explicitly mentioned in this thread is that
> when you make those modules to hold classes DO NOT make the module name
> the same as the class name.
> 
> If you have a class MyClass defined in your 10k file, and you want to
> move it to a separate file, and if you really wanted to dedicate the
> file to a single class, then the file might be called myclass.py and the
> references to it would like something like:
> 
> import myclass
> ...
> obj = myclass.MyClass(arg1, arg2)
> 
> or alternatively,
> 
> from myclass import MyClass
> ...
> obj = MyClass(arg1, arg2)
> 
> You wouldn't believe how much confusion people get into when they have
> module names that look like class names.
> 
> 
> Another thing is that you probably want several related classes and
> functions in each module.  This is not Java.  At that point, you might want
> 
> from  people  import MyFirstPeopleClass, MySecondPeopleClass, peoplefunction
> 
> 
> Finally, upon more careful reading of your original query, you may have
> circular dependencies happening here.  A function may use class methods,
> and class methods may use the function.  But if both are true, then put
> them in the same module.  Having one module import a second one which
> imports the first is an invitation to disaster.  And a special place in
> debugging hell is reserved for those that try to import the script that
> invokes it all.
> 
> -- 
> 
> DaveA
> 

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


Re: [Tutor] updating step size while in loop

2012-07-09 Thread Abhishek Pratap
Ok thanks Hugo. I have the while loop working

-A

On Mon, Jul 9, 2012 at 3:06 PM, Hugo Arts  wrote:
> On Mon, Jul 9, 2012 at 11:59 PM, Abhishek Pratap 
> wrote:
>>
>> hey guys
>>
>> I want to know whether it is possible for dynamically update the step
>> size in xrange  or someother slick way.
>>
>> Here is what I am trying to do, if during a loop I find the x in list
>> I want to skip next #n iterations.
>>
>>
>> for x in xrange(start,stop,step):
>> if x in list:
>>  step = 14
>> else:
>>  step = 1
>>
>>
>>
>> Thanks!
>> -Abhi
>
>
> It is not possible with a range object. You'll have to make a while loop and
> keep track of the step yourself.
>
> Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] confusion about imports

2012-07-09 Thread Dave Angel
On 07/09/2012 11:56 AM, Chris Hare wrote:
> So, I have to admit, imports have me really confused.  I am trying to break 
> apart a 10,000+ line single file into various files, one for each class, and 
> one containing a whole bunch of functions which are used by a lot of classes. 
>  Some of those functions use calls to methods in a Class.  Even though the 
> Class has been imported, I get a nameError where trying to use the class.  I 
> have read about Classes and packages and modules, but import just has me 
> confused.
Something I haven't seen explicitly mentioned in this thread is that
when you make those modules to hold classes DO NOT make the module name
the same as the class name.

If you have a class MyClass defined in your 10k file, and you want to
move it to a separate file, and if you really wanted to dedicate the
file to a single class, then the file might be called myclass.py and the
references to it would like something like:

import myclass
...
obj = myclass.MyClass(arg1, arg2)

or alternatively,

from myclass import MyClass
...
obj = MyClass(arg1, arg2)

You wouldn't believe how much confusion people get into when they have
module names that look like class names.


Another thing is that you probably want several related classes and
functions in each module.  This is not Java.  At that point, you might want

from  people  import MyFirstPeopleClass, MySecondPeopleClass, peoplefunction


Finally, upon more careful reading of your original query, you may have
circular dependencies happening here.  A function may use class methods,
and class methods may use the function.  But if both are true, then put
them in the same module.  Having one module import a second one which
imports the first is an invitation to disaster.  And a special place in
debugging hell is reserved for those that try to import the script that
invokes it all.

-- 

DaveA

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


Re: [Tutor] updating step size while in loop

2012-07-09 Thread Hugo Arts
On Mon, Jul 9, 2012 at 11:59 PM, Abhishek Pratap wrote:

> hey guys
>
> I want to know whether it is possible for dynamically update the step
> size in xrange  or someother slick way.
>
> Here is what I am trying to do, if during a loop I find the x in list
> I want to skip next #n iterations.
>
>
> for x in xrange(start,stop,step):
> if x in list:
>  step = 14
> else:
>  step = 1
>
>
>
> Thanks!
> -Abhi
>

It is not possible with a range object. You'll have to make a while loop
and keep track of the step yourself.

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


[Tutor] updating step size while in loop

2012-07-09 Thread Abhishek Pratap
hey guys

I want to know whether it is possible for dynamically update the step
size in xrange  or someother slick way.

Here is what I am trying to do, if during a loop I find the x in list
I want to skip next #n iterations.


for x in xrange(start,stop,step):
if x in list:
 step = 14
else:
 step = 1



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


Re: [Tutor] Mapping ID's for corresponding values in different Columns

2012-07-09 Thread Fred G
Sorry, just got that as well.  It was the placement of the if-statement in
the nested for-loop.  so v was stuck on 3...thanks again for the help with
this!!!

On Mon, Jul 9, 2012 at 1:57 PM, Fred G  wrote:

> Got it! Thanks guys for all your help--what a satisfying feeling!  Just
> out of curiosity, in the following:
>
> def new_dict (csv_to_dict, nested_line):
> old_dict = csv_to_dict(file1)
> old_list = nested_line(file2)
> new_dict = {}
> #for item in old_list:
> #new_dict[item] = item
> for k, v in old_dict.iteritems():
> for item in old_list:
> if k == item:
> new_dict[item] = v
> return (new_dict)
>
> when I deleted the third line from the bottom (the "if k == item"), I got
> the same value ("3") for each key, instead of the correct output (ie the
> different ID's).  Does anyone know why this was the case?
>
> Thanks so much.
>
>
> On Mon, Jul 9, 2012 at 8:23 AM, Fred G  wrote:
>
>> Thank you guys so much.  I'm quite close now, but I'm having a bit of
>> trouble on the final for-loop to create the new dictionary.  I have the
>> following 3 functions (note I'm re-typing it from a different computer so
>> while the identation will be off here, it is correct in the actual code):
>>
>> #read in file as dictionary.  Name is key, id is value.
>> def csv_to_dict(filename):
>>   record = {}
>>   line = filename.readline()
>>   for line in filename:
>> key = line.split(",", 1)[-1]
>> val = line.split(",", 1)[:-1]
>>   return record
>>
>> #read in file2 names
>> def nested_line(filename):
>>   line = filename.readline()
>>   new_list = []
>>   for line in filename:
>> name = line.split(",", 1)[-1]
>> new_list.append(name)
>>   return new_list
>>
>> #this is the function that I'm having trouble with
>> #create new dict mapping file 1 ids to file2's names
>> def new_dict (csv_to_dict, nested_line):
>>   old_dict = cssv_to_dict(file1)
>>   old_list = nested_line(file2)
>>   new_dict1 = {}
>>   for item in old_list:
>> new_dict1[item] = item
>>   return (new_dict1)
>>
>> I have tried various permutations of the for loop in this final function,
>> but I haven't quite gotten it.  The current form is the closest I have
>> gotten to my desired output, since it produces the new dictionary with the
>> name that I want-- just an invalid id associated with that name.  I tried a
>> bunch of different nested loops but kept getting it incorrect and then
>> after so many attempts I got a little confused about what I was trying to
>> do.  So I backed up a little bit and have this.
>>
>> Conceptually, I thought that this would give me my desired result:
>> new_dict
>> for name in old_list:
>>   for key, value in old_dict:
>> if name == key:
>>   new_dict1[key] = value
>> return(new_dict1)
>>
>> But it wasn't right.  I tried a different approach where I used the
>> dict.values() function in order to pull out the values from old_dict that
>> we want to include in the new_dict, but I got a bit lost there, too.
>>
>> I'm so close right now and I would be so thankful for any bit of
>> clarification which could get me to the finish line.
>>
>> On Mon, Jul 9, 2012 at 12:42 AM, Hugo Arts  wrote:
>>
>>> On Sun, Jul 8, 2012 at 11:47 PM, Fred G  wrote:
>>>
 Hi--

 My current input looks like the following:

 FILE1.csv
 PERSON_IDPERSON_NAME
 1 Jen
 2 Mike
 3 Jim
 4
 5 Jane
 6 Joe
 7 Jake

 FILE2.csv
 PERSON_ID   PERSON_NAME
  Jim
  Mike
  Jane
  Todd
  Jen

 _
 I want to fill into the PERSON_ID column of FILE2.csv the corresponding
 ID's associated with those names as identified in FILE1.csv.

 At first I imported the csv module and was using the csv.Reader, but
 then it seemed simple enough just to write something like:
 for line in file2:
  print(line)

 giving me the following output:
 PERSON_ID, PERSON_NAME
 , Jim
 , Mike
 , Jane
 , Todd
 , Jen

 I think I understand the issue at a conceptual level, but not quite
 sure how to fully implement it:
 a) I want to build a dictionary to create keys, such that each number
 in file1 corresponds to a unique string in column B of file1.
 b) then write a for loop like the following:
 for "person_name" in file2:
if "person_name.file2" == "person_name.file1":
person_id.file2 == person_id.file1
 c) write into file2 the changes to person_id's...

 But it's pretty difficult for me to get past this stage. Am I on the
 right track? And more importantly, how could I learn how to actually
 implement this in smaller stages?


>>>  You're on the right track,

Re: [Tutor] Mapping ID's for corresponding values in different Columns

2012-07-09 Thread Fred G
Got it! Thanks guys for all your help--what a satisfying feeling!  Just out
of curiosity, in the following:

def new_dict (csv_to_dict, nested_line):
old_dict = csv_to_dict(file1)
old_list = nested_line(file2)
new_dict = {}
#for item in old_list:
#new_dict[item] = item
for k, v in old_dict.iteritems():
for item in old_list:
if k == item:
new_dict[item] = v
return (new_dict)

when I deleted the third line from the bottom (the "if k == item"), I got
the same value ("3") for each key, instead of the correct output (ie the
different ID's).  Does anyone know why this was the case?

Thanks so much.


On Mon, Jul 9, 2012 at 8:23 AM, Fred G  wrote:

> Thank you guys so much.  I'm quite close now, but I'm having a bit of
> trouble on the final for-loop to create the new dictionary.  I have the
> following 3 functions (note I'm re-typing it from a different computer so
> while the identation will be off here, it is correct in the actual code):
>
> #read in file as dictionary.  Name is key, id is value.
> def csv_to_dict(filename):
>   record = {}
>   line = filename.readline()
>   for line in filename:
> key = line.split(",", 1)[-1]
> val = line.split(",", 1)[:-1]
>   return record
>
> #read in file2 names
> def nested_line(filename):
>   line = filename.readline()
>   new_list = []
>   for line in filename:
> name = line.split(",", 1)[-1]
> new_list.append(name)
>   return new_list
>
> #this is the function that I'm having trouble with
> #create new dict mapping file 1 ids to file2's names
> def new_dict (csv_to_dict, nested_line):
>   old_dict = cssv_to_dict(file1)
>   old_list = nested_line(file2)
>   new_dict1 = {}
>   for item in old_list:
> new_dict1[item] = item
>   return (new_dict1)
>
> I have tried various permutations of the for loop in this final function,
> but I haven't quite gotten it.  The current form is the closest I have
> gotten to my desired output, since it produces the new dictionary with the
> name that I want-- just an invalid id associated with that name.  I tried a
> bunch of different nested loops but kept getting it incorrect and then
> after so many attempts I got a little confused about what I was trying to
> do.  So I backed up a little bit and have this.
>
> Conceptually, I thought that this would give me my desired result:
> new_dict
> for name in old_list:
>   for key, value in old_dict:
> if name == key:
>   new_dict1[key] = value
> return(new_dict1)
>
> But it wasn't right.  I tried a different approach where I used the
> dict.values() function in order to pull out the values from old_dict that
> we want to include in the new_dict, but I got a bit lost there, too.
>
> I'm so close right now and I would be so thankful for any bit of
> clarification which could get me to the finish line.
>
> On Mon, Jul 9, 2012 at 12:42 AM, Hugo Arts  wrote:
>
>> On Sun, Jul 8, 2012 at 11:47 PM, Fred G  wrote:
>>
>>> Hi--
>>>
>>> My current input looks like the following:
>>>
>>> FILE1.csv
>>> PERSON_IDPERSON_NAME
>>> 1 Jen
>>> 2 Mike
>>> 3 Jim
>>> 4
>>> 5 Jane
>>> 6 Joe
>>> 7 Jake
>>>
>>> FILE2.csv
>>> PERSON_ID   PERSON_NAME
>>>  Jim
>>>  Mike
>>>  Jane
>>>  Todd
>>>  Jen
>>>
>>> _
>>> I want to fill into the PERSON_ID column of FILE2.csv the corresponding
>>> ID's associated with those names as identified in FILE1.csv.
>>>
>>> At first I imported the csv module and was using the csv.Reader, but
>>> then it seemed simple enough just to write something like:
>>> for line in file2:
>>>  print(line)
>>>
>>> giving me the following output:
>>> PERSON_ID, PERSON_NAME
>>> , Jim
>>> , Mike
>>> , Jane
>>> , Todd
>>> , Jen
>>>
>>> I think I understand the issue at a conceptual level, but not quite sure
>>> how to fully implement it:
>>> a) I want to build a dictionary to create keys, such that each number in
>>> file1 corresponds to a unique string in column B of file1.
>>> b) then write a for loop like the following:
>>> for "person_name" in file2:
>>>if "person_name.file2" == "person_name.file1":
>>>person_id.file2 == person_id.file1
>>> c) write into file2 the changes to person_id's...
>>>
>>> But it's pretty difficult for me to get past this stage. Am I on the
>>> right track? And more importantly, how could I learn how to actually
>>> implement this in smaller stages?
>>>
>>>
>>  You're on the right track, and you're almost there! You've already
>> broken down the problem into steps. You should now try to implement a
>> function for each step, and finally you should glue these functions
>> together into a final program.
>>
>> a) Though you don't *have* to use it, csv.reader is really quite simple,
>> I'd recommend it. Try and write a function that takes a file na

Re: [Tutor] confusion about imports

2012-07-09 Thread David Rock
* Chris Hare  [2012-07-09 13:33]:

> import functions
> import os
> import db
> 
> when everything was all in one file, that worked just fine.  Now, with it all 
> split up, once I changed
> 
> r = DbPath()
> 
> to
> 
> r = functions.DbPath()
> 
> things seems to work now.  I hope this is it!!!
> 

Yes, that's it.  As mentioned elsewhere, you have to reference the
module name in order to let python know _which_ one you want.

For example, you could have the same DbPath() method in two different
modules: module1 and  module2, so you need to be able to differentiate.

module1.DbPath() is not the same thing as module2.DbPath()

Your functions.DbPath() is the way to go.

-- 
David Rock
da...@graniteweb.com


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


Re: [Tutor] confusion about imports

2012-07-09 Thread Chris Hare

On Jul 9, 2012, at 12:42 PM, Walter Prins wrote:

> Hi Chris
> 
>> So, I have to admit, imports have me really confused.  I am trying to break 
>> apart a 10,000+ line single file into various files, one for each class, and 
>> one containing a whole bunch of functions which are used by a lot of 
>> classes.  Some of those functions use calls to methods in a Class.  Even 
>> though the Class has been imported, I get a nameError where trying to use 
>> the class.  I have read about Classes and packages and modules, but import 
>> just has me confused.
> 
> How did you import the class?  Or did you perhaps not import the Class
> itself, but rather the module containing the class?

I am doing import NAME where name is not only the name of the class, but also 
the name of the file containing the class.  The only reasons I am trying to 
break up the file is because it is getting to difficult to find stuff.  Some of 
the content hasn't change while other parts are still in flux a lot.  I figured 
that splitting it into the various files will make it easier to edit.

so I think I have figured out the problem based upon the resources you 
specified - the first one helped a bunch.

I was using 

import functions
import os
import db

when everything was all in one file, that worked just fine.  Now, with it all 
split up, once I changed

r = DbPath()

to

r = functions.DbPath()

things seems to work now.  I hope this is it!!!

Now, I have a bunch of smaller, more manageable files instead of trying to edit 
one ginormous one :-)

Thanks!

> 
> Read this article which explains a bit about Python namespaces:
> http://is.gd/e8PAZW  (but I note there's a bit of conflation of
> "class" and "class instance" going on at the end.)
> 
> Also read this page from the Python documentation, section "Python
> Scopes and Namespaces": http://docs.python.org/tutorial/classes.html
> 
> If a class is defined in a module (e.g. in the namespace of the
> module), and you "import module" the module into the your current
> namespace, then from within the current namespace you can access the
> class with "module.Class".  If however you import the class itself,
> e.g. "from module import Class", into your current namespace, then the
> Class itself is directly part of your local namespace and you must
> therefore access it unqualified as just "Class".

Thanks for the links -- yep - it helped, although I haven't solved my specific 
problem yet.
> 
> HTH,
> 
> Walter
> ___
> 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] confusion about imports

2012-07-09 Thread Mark Lawrence

On 09/07/2012 16:56, Chris Hare wrote:


So, I have to admit, imports have me really confused.  I am trying to break 
apart a 10,000+ line single file into various files, one for each class, and 
one containing a whole bunch of functions which are used by a lot of classes.  
Some of those functions use calls to methods in a Class.  Even though the Class 
has been imported, I get a nameError where trying to use the class.  I have 
read about Classes and packages and modules, but import just has me confused.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



Please don't break the file up for the sake of doing it, you're writing 
python not java :-)


--
Cheers.

Mark Lawrence.



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


Re: [Tutor] confusion about imports

2012-07-09 Thread Walter Prins
Hi Chris

> So, I have to admit, imports have me really confused.  I am trying to break 
> apart a 10,000+ line single file into various files, one for each class, and 
> one containing a whole bunch of functions which are used by a lot of classes. 
>  Some of those functions use calls to methods in a Class.  Even though the 
> Class has been imported, I get a nameError where trying to use the class.  I 
> have read about Classes and packages and modules, but import just has me 
> confused.

How did you import the class?  Or did you perhaps not import the Class
itself, but rather the module containing the class?

Read this article which explains a bit about Python namespaces:
http://is.gd/e8PAZW  (but I note there's a bit of conflation of
"class" and "class instance" going on at the end.)

Also read this page from the Python documentation, section "Python
Scopes and Namespaces": http://docs.python.org/tutorial/classes.html

If a class is defined in a module (e.g. in the namespace of the
module), and you "import module" the module into the your current
namespace, then from within the current namespace you can access the
class with "module.Class".  If however you import the class itself,
e.g. "from module import Class", into your current namespace, then the
Class itself is directly part of your local namespace and you must
therefore access it unqualified as just "Class".

HTH,

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


Re: [Tutor] confusion about imports

2012-07-09 Thread Joel Goldstick
On Mon, Jul 9, 2012 at 11:56 AM, Chris Hare  wrote:
>
> So, I have to admit, imports have me really confused.  I am trying to break 
> apart a 10,000+ line single file into various files, one for each class, and 
> one containing a whole bunch of functions which are used by a lot of classes. 
>  Some of those functions use calls to methods in a Class.  Even though the 
> Class has been imported, I get a nameError where trying to use the class.  I 
> have read about Classes and packages and modules, but import just has me 
> confused.


a 10k line file is a scary thought!  Can you make a very small example
that shows your problem.  Something like

import whatever

my_thing = whatever.classname()


and tell us if you get the error?

This is a wild guess, but from reading your question I'm wondering if
you are instantiating the class?
-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] confusion about imports

2012-07-09 Thread Chris Hare

So, I have to admit, imports have me really confused.  I am trying to break 
apart a 10,000+ line single file into various files, one for each class, and 
one containing a whole bunch of functions which are used by a lot of classes.  
Some of those functions use calls to methods in a Class.  Even though the Class 
has been imported, I get a nameError where trying to use the class.  I have 
read about Classes and packages and modules, but import just has me confused.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] TypeError: not all arguments converted during string formatting

2012-07-09 Thread Steven D'Aprano

Keitaro Kaoru wrote:
[...]

TypeError: not all arguments converted during string formatting

[...]

return self.html % ca

cant seem to find out whats wrong with it



Try experimenting at the interactive interpreter:


[steve@ando ~]$ python
Python 2.6.7 (r267:88850, Mar 10 2012, 12:32:58)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
py> "%s - %s - %s" % (1, 2, 3)
'1 - 2 - 3'

py> "%s - %s - %s" % (1, 2)  # Not enough values
Traceback (most recent call last):
  File "", line 1, in 
TypeError: not enough arguments for format string

py> "%s - %s - %s" % (1, 2, 3, 4)  # Too many values
Traceback (most recent call last):
  File "", line 1, in 
TypeError: not all arguments converted during string formatting


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


Re: [Tutor] TypeError: not all arguments converted during string formatting

2012-07-09 Thread Joel Goldstick
On Mon, Jul 9, 2012 at 11:31 AM, Keitaro Kaoru  wrote:
> Traceback (most recent call last):
>   File "bot.py", line 351, in 
> mgr.main()
>   File "/home/bot/bot/ch.py", line 1672, in main
> con._feed(data)
>   File "/home/bot/bot/ch.py", line 628, in _feed
> self._process(food.decode("latin-1").rstrip("\r\n")) #numnumz ;3
>   File "/home/bot/bot/ch.py", line 643, in _process
> getattr(self, func)(args)
>   File "/home/bot/bot/ch.py", line 744, in rcmd_u
> self._callEvent("onMessage", msg.user, msg)
>   File "/home/bot/bot/ch.py", line 1091, in _callEvent
> self.mgr.onEventCalled(self, evt, *args, **kw)
>   File "bot.py", line 287, in onEventCalled
> self.invokeListeners(room, evt, *args, **kw)
>   File "bot.py", line 110, in invokeListeners
> getattr(lis, evt)(self, room, *args, **kw)
>   File "modules/lulz2.py", line 47, in onMessage
> self.sendObject(room, ret)
>   File "bot.py", line 307, in sendObject
> obj = obj.__botOut__(self, room)
>   File "/home/bot/bot/tools.py", line 226, in __botOut__
> return self.html % ca
> TypeError: not all arguments converted during string formatting
>
>
>
>
> class Text:
> def __init__(self, text):
> self.text = text
>
> def __botOut__(self, mgr, room):
> return cgi.escape(self.text)
>
> class Html:
> def __init__(self, html, *args):
> self.html = html
> self.args = args
>
> def __botOut__(self, mgr, room):
> if len(self.args) == 0:
> return self.html
> else:
> ca = tuple([cgi.escape(arg) if type(arg) == str else 
> arg for arg in
> self.args])
> return self.html % ca
>
> cant seem to find out whats wrong with it

You don't show what self.html is.  It must have the same number of %s
values as the length of ca
> --
> ~~Austin
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



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


[Tutor] TypeError: not all arguments converted during string formatting

2012-07-09 Thread Keitaro Kaoru
Traceback (most recent call last):
  File "bot.py", line 351, in 
mgr.main()
  File "/home/bot/bot/ch.py", line 1672, in main
con._feed(data)
  File "/home/bot/bot/ch.py", line 628, in _feed
self._process(food.decode("latin-1").rstrip("\r\n")) #numnumz ;3
  File "/home/bot/bot/ch.py", line 643, in _process
getattr(self, func)(args)
  File "/home/bot/bot/ch.py", line 744, in rcmd_u
self._callEvent("onMessage", msg.user, msg)
  File "/home/bot/bot/ch.py", line 1091, in _callEvent
self.mgr.onEventCalled(self, evt, *args, **kw)
  File "bot.py", line 287, in onEventCalled
self.invokeListeners(room, evt, *args, **kw)
  File "bot.py", line 110, in invokeListeners
getattr(lis, evt)(self, room, *args, **kw)
  File "modules/lulz2.py", line 47, in onMessage
self.sendObject(room, ret)
  File "bot.py", line 307, in sendObject
obj = obj.__botOut__(self, room)
  File "/home/bot/bot/tools.py", line 226, in __botOut__
return self.html % ca
TypeError: not all arguments converted during string formatting




class Text:
def __init__(self, text):
self.text = text

def __botOut__(self, mgr, room):
return cgi.escape(self.text)

class Html:
def __init__(self, html, *args):
self.html = html
self.args = args

def __botOut__(self, mgr, room):
if len(self.args) == 0:
return self.html
else:
ca = tuple([cgi.escape(arg) if type(arg) == str else 
arg for arg in
self.args])
return self.html % ca

cant seem to find out whats wrong with it
-- 
~~Austin
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mapping ID's for corresponding values in different Columns

2012-07-09 Thread Fred G
Thank you guys so much.  I'm quite close now, but I'm having a bit of
trouble on the final for-loop to create the new dictionary.  I have the
following 3 functions (note I'm re-typing it from a different computer so
while the identation will be off here, it is correct in the actual code):

#read in file as dictionary.  Name is key, id is value.
def csv_to_dict(filename):
  record = {}
  line = filename.readline()
  for line in filename:
key = line.split(",", 1)[-1]
val = line.split(",", 1)[:-1]
  return record

#read in file2 names
def nested_line(filename):
  line = filename.readline()
  new_list = []
  for line in filename:
name = line.split(",", 1)[-1]
new_list.append(name)
  return new_list

#this is the function that I'm having trouble with
#create new dict mapping file 1 ids to file2's names
def new_dict (csv_to_dict, nested_line):
  old_dict = cssv_to_dict(file1)
  old_list = nested_line(file2)
  new_dict1 = {}
  for item in old_list:
new_dict1[item] = item
  return (new_dict1)

I have tried various permutations of the for loop in this final function,
but I haven't quite gotten it.  The current form is the closest I have
gotten to my desired output, since it produces the new dictionary with the
name that I want-- just an invalid id associated with that name.  I tried a
bunch of different nested loops but kept getting it incorrect and then
after so many attempts I got a little confused about what I was trying to
do.  So I backed up a little bit and have this.

Conceptually, I thought that this would give me my desired result:
new_dict
for name in old_list:
  for key, value in old_dict:
if name == key:
  new_dict1[key] = value
return(new_dict1)

But it wasn't right.  I tried a different approach where I used the
dict.values() function in order to pull out the values from old_dict that
we want to include in the new_dict, but I got a bit lost there, too.

I'm so close right now and I would be so thankful for any bit of
clarification which could get me to the finish line.

On Mon, Jul 9, 2012 at 12:42 AM, Hugo Arts  wrote:

> On Sun, Jul 8, 2012 at 11:47 PM, Fred G  wrote:
>
>> Hi--
>>
>> My current input looks like the following:
>>
>> FILE1.csv
>> PERSON_IDPERSON_NAME
>> 1 Jen
>> 2 Mike
>> 3 Jim
>> 4
>> 5 Jane
>> 6 Joe
>> 7 Jake
>>
>> FILE2.csv
>> PERSON_ID   PERSON_NAME
>>  Jim
>>  Mike
>>  Jane
>>  Todd
>>  Jen
>>
>> _
>> I want to fill into the PERSON_ID column of FILE2.csv the corresponding
>> ID's associated with those names as identified in FILE1.csv.
>>
>> At first I imported the csv module and was using the csv.Reader, but then
>> it seemed simple enough just to write something like:
>> for line in file2:
>>  print(line)
>>
>> giving me the following output:
>> PERSON_ID, PERSON_NAME
>> , Jim
>> , Mike
>> , Jane
>> , Todd
>> , Jen
>>
>> I think I understand the issue at a conceptual level, but not quite sure
>> how to fully implement it:
>> a) I want to build a dictionary to create keys, such that each number in
>> file1 corresponds to a unique string in column B of file1.
>> b) then write a for loop like the following:
>> for "person_name" in file2:
>>if "person_name.file2" == "person_name.file1":
>>person_id.file2 == person_id.file1
>> c) write into file2 the changes to person_id's...
>>
>> But it's pretty difficult for me to get past this stage. Am I on the
>> right track? And more importantly, how could I learn how to actually
>> implement this in smaller stages?
>>
>>
>  You're on the right track, and you're almost there! You've already broken
> down the problem into steps. You should now try to implement a function for
> each step, and finally you should glue these functions together into a
> final program.
>
> a) Though you don't *have* to use it, csv.reader is really quite simple,
> I'd recommend it. Try and write a function that takes a file name as
> argument and returns a dictionary of the form { name: id, name: id } (i.e.
> the names are the keys).
>
> b) For this step, you first need a list of all names in file 2. You could
> use csv.reader again or you could just parse it. Then, you use the
> dictionary to look up the corresponding id. The end goal for this function
> is to return a list of lists that looks much like the file you want to end
> up with:
>
> [[id, name],
>  [id, name],
>  [id, name]]
>
> c) this step should now be easy. I'd again, recommend csv.writer, it makes
> the process pretty simple. You just pass in the nested list from step (b)
> and you're pretty much done.
>
> For tips on the csv module, the list of examples is pretty helpful:
> http://docs.python.org/py3k/library/csv.html#examples
> If you need help constructing the lists and dictionaries, my tips would be
> 1) think one row at a time

Re: [Tutor] using dynamic import statements

2012-07-09 Thread wolfrage8...@gmail.com
Might I recommend you use the logging module that is part of core
Python rather than rolling your own if Debug. I found the logging
module made growing my logging across multiple applications so easy!
http://docs.python.org/library/logging.html

On Mon, Jul 9, 2012 at 2:10 PM, Chris Hare  wrote:
>
> Thanks all for the ideas.  I wanted to have my own error messages printed for 
> the user - something a little more meaningful than the standard error.
>
> Thanks for the advice - very helpful!
>
> On Jul 9, 2012, at 6:12 AM, Alan Gauld wrote:
>
>> On 09/07/12 10:19, Kwpolska wrote:
>>> Why does this bloody ML want me to respond to the last person instead
>>> of tutor@python.org?
>>
>> Because that's how it, along with many other mailing lists, works.
>> If it helps, think of it as you receiving a mail from the sender and CCd to 
>> the list. Therefore hitting reply sends to the person who sent the mail and 
>> ReplyAll goes to everyone. Seems logical to me! :-)
>> It allows me to choose to reply to the OP only or to the group, I use both 
>> depending on the nature of my reply. (About 80% of my replies go to the 
>> everyone.) But some prefer it differently... :-)
>>
 Why not the more usual:

 import sys, os, imp, stat,\
re, webbrowser, Image, \
StringIO, shutil, datetime
>>>
>>> Why not the more standard:
>>> import sys
>>> import os
>>> and so on?  http://www.python.org/dev/peps/pep-0008/#imports
>>
>> Indeed but the OP seemed to want to remove duplicate coding so I assumed 
>> that he included using multiple imports.
>>
>> Personally I'd probably code the above as:
>>
>> import sys, os, shutil, stat, datetime
>> import re, StringIO
>> import webbrowser,
>> import Image,
>> import imp
>>
>> Which groups things into roughly related categories - system,
>> strings, other...
>>
>> OTOH I ignore large chunks of Pep 8 because I find its style harder to read 
>> than the one I'm used to. But then, I'm not contributing to the standard 
>> library etc... Style is largely a matter of taste.
>>
>> --
>> Alan G
>> 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
>
> ___
> 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] using dynamic import statements

2012-07-09 Thread Chris Hare

Thanks all for the ideas.  I wanted to have my own error messages printed for 
the user - something a little more meaningful than the standard error. 

Thanks for the advice - very helpful!

On Jul 9, 2012, at 6:12 AM, Alan Gauld wrote:

> On 09/07/12 10:19, Kwpolska wrote:
>> Why does this bloody ML want me to respond to the last person instead
>> of tutor@python.org?
> 
> Because that's how it, along with many other mailing lists, works.
> If it helps, think of it as you receiving a mail from the sender and CCd to 
> the list. Therefore hitting reply sends to the person who sent the mail and 
> ReplyAll goes to everyone. Seems logical to me! :-)
> It allows me to choose to reply to the OP only or to the group, I use both 
> depending on the nature of my reply. (About 80% of my replies go to the 
> everyone.) But some prefer it differently... :-)
> 
>>> Why not the more usual:
>>> 
>>> import sys, os, imp, stat,\
>>>re, webbrowser, Image, \
>>>StringIO, shutil, datetime
>> 
>> Why not the more standard:
>> import sys
>> import os
>> and so on?  http://www.python.org/dev/peps/pep-0008/#imports
> 
> Indeed but the OP seemed to want to remove duplicate coding so I assumed that 
> he included using multiple imports.
> 
> Personally I'd probably code the above as:
> 
> import sys, os, shutil, stat, datetime
> import re, StringIO
> import webbrowser,
> import Image,
> import imp
> 
> Which groups things into roughly related categories - system,
> strings, other...
> 
> OTOH I ignore large chunks of Pep 8 because I find its style harder to read 
> than the one I'm used to. But then, I'm not contributing to the standard 
> library etc... Style is largely a matter of taste.
> 
> -- 
> Alan G
> 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

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


Re: [Tutor] Reading a csv of coordinates, trying to write a csv of bearings.

2012-07-09 Thread Joel Goldstick
On Mon, Jul 9, 2012 at 3:14 AM, Hugo Arts  wrote:
> On Mon, Jul 9, 2012 at 3:10 AM, Gregory Lund  wrote:
>>
>> I'm Not looking for an absolute solution, but perhaps some insight
>> into some snippets of code, or
>> suggestions of where I should seek out answers to this issue.
>> Or where I've gone wrong below.

1. Look at the csv module.  It makes dealing with csv very convenient.
2. The fact that every other line in your input file is blank will
require you to through out those lines.  One way to do this is with
slicing:
>>> a = [0,1,2,3,4,5,6]
>>> b = a[::2]
>>> b
[0, 2, 4, 6]
>>>
3. I would read the input into a list of lists (each line item is in a
list, each line is in the containing list
4. get rid of the blanks
5. make a function to take the input lists and do your math,
producting a list of lists to be output
6. use the csv writer to write to a file
7. You have way to many comments in your code.  At the top of your
file, and immediately underneath each function definition use
docstrings (triple quoted multi-line strings).  These are great in
that they provide automatic documentation for your functions using
pydocs, or when you are in the python shell you can do
help(function_name) and find out what it does



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


Re: [Tutor] using dynamic import statements

2012-07-09 Thread Alan Gauld

On 09/07/12 10:19, Kwpolska wrote:

Why does this bloody ML want me to respond to the last person instead
of tutor@python.org?


Because that's how it, along with many other mailing lists, works.
If it helps, think of it as you receiving a mail from the sender and CCd 
to the list. Therefore hitting reply sends to the person who sent the 
mail and ReplyAll goes to everyone. Seems logical to me! :-)
It allows me to choose to reply to the OP only or to the group, I use 
both depending on the nature of my reply. (About 80% of my replies go to 
the everyone.) But some prefer it differently... :-)



Why not the more usual:

import sys, os, imp, stat,\
re, webbrowser, Image, \
StringIO, shutil, datetime


Why not the more standard:
import sys
import os
and so on?  http://www.python.org/dev/peps/pep-0008/#imports


Indeed but the OP seemed to want to remove duplicate coding so I assumed 
that he included using multiple imports.


Personally I'd probably code the above as:

import sys, os, shutil, stat, datetime
import re, StringIO
import webbrowser,
import Image,
import imp

Which groups things into roughly related categories - system,
strings, other...

OTOH I ignore large chunks of Pep 8 because I find its style harder to 
read than the one I'm used to. But then, I'm not contributing to the 
standard library etc... Style is largely a matter of taste.


--
Alan G
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] using dynamic import statements

2012-07-09 Thread Kwpolska
Why does this bloody ML want me to respond to the last person instead
of tutor@python.org?
---
On Mon, Jul 9, 2012 at 9:47 AM, Alan Gauld  wrote:
> On 09/07/12 02:10, Chris Hare wrote:
>>
>>
>> Here is what I want to do:
>>
>> I have a bunch of modules to import. instead of duplicating
>
>> a lot of code for each import, I want to do something like this:
>
> ...lots of code stripped
>
>
> Why not the more usual:
>
> import sys, os, imp, stat,\
>re, webbrowser, Image, \
>StringIO, shutil, datetime
>
> [snip]

Why not the more standard:
import sys
import os
and so on?  http://www.python.org/dev/peps/pep-0008/#imports
-- 
Kwpolska 
stop html mail  | always bottom-post
www.asciiribbon.org | www.netmeister.org/news/learn2quote.html
GPG KEY: 5EAAEA16   | Arch Linux x86_64, zsh, mutt, vim.
# vim:set textwidth=70:
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using dynamic import statements

2012-07-09 Thread ankur ~ अंकुर
On Mon, Jul 9, 2012 at 6:40 AM, Chris Hare  wrote:

>
> Here is what I want to do:
>
> I have a bunch of modules to import. instead of duplicating a lot of code
> for each import, I want to do something like this:
>
> importList = [ "sys", "os", "imp", "stat", "re", "webbrowser", "Image",
>  "StringIO", "shutil", "datetime" ]
>
> for object in importList:
> try:
> if debug == "ON":
> print "Importing module %s" % (object)
> exec( "import  " + object)
> except ImportError as error:
> print "%s %s requires the Python %s library.  " % (
> appName,
>
> str(appVersion), object )
> print "An error occurred when attempting to load the
> library.  The error was '%s'." % ( error )
> exit()
>
> Everything "appears" to run okay, however, when the first piece of code
> that relies upon one of these imported modules is executed, I get an error:
>
> Traceback (most recent call last):
>   File "a.py", line 122, in 
> imp.load_module(object,fp,pathName,description)
>   File "./Modules/functions.py", line 133, in 
> def special_match(strg, search=re.compile(r'[^a-zA-Z0-9\.\
> \-\#\$\*\@\!\%\^\&]').search):
> NameError: name 're' is not defined
>
> Is is possible to do what I am trying to do, or am I doing something wrong?
>
> Thanks
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Hi,

How about using import imp
http://docs.python.org/library/imp.html

calling run time modules as per your need.

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


Re: [Tutor] using dynamic import statements

2012-07-09 Thread Alan Gauld

On 09/07/12 02:10, Chris Hare wrote:


Here is what I want to do:

I have a bunch of modules to import. instead of duplicating

> a lot of code for each import, I want to do something like this:

...lots of code stripped


Why not the more usual:

import sys, os, imp, stat,\
   re, webbrowser, Image, \
   StringIO, shutil, datetime

And let the Python ImportError alert you to what failed?

Or if you must print your own errors just use

try:
   import ...
except ImportError:
   # your code here

I'm not sure what code you think you need to duplicate or why.

--
Alan G
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] Mapping ID's for corresponding values in different Columns

2012-07-09 Thread Hugo Arts
On Sun, Jul 8, 2012 at 11:47 PM, Fred G  wrote:

> Hi--
>
> My current input looks like the following:
>
> FILE1.csv
> PERSON_IDPERSON_NAME
> 1 Jen
> 2 Mike
> 3 Jim
> 4
> 5 Jane
> 6 Joe
> 7 Jake
>
> FILE2.csv
> PERSON_ID   PERSON_NAME
>  Jim
>  Mike
>  Jane
>  Todd
>  Jen
>
> _
> I want to fill into the PERSON_ID column of FILE2.csv the corresponding
> ID's associated with those names as identified in FILE1.csv.
>
> At first I imported the csv module and was using the csv.Reader, but then
> it seemed simple enough just to write something like:
> for line in file2:
>  print(line)
>
> giving me the following output:
> PERSON_ID, PERSON_NAME
> , Jim
> , Mike
> , Jane
> , Todd
> , Jen
>
> I think I understand the issue at a conceptual level, but not quite sure
> how to fully implement it:
> a) I want to build a dictionary to create keys, such that each number in
> file1 corresponds to a unique string in column B of file1.
> b) then write a for loop like the following:
> for "person_name" in file2:
>if "person_name.file2" == "person_name.file1":
>person_id.file2 == person_id.file1
> c) write into file2 the changes to person_id's...
>
> But it's pretty difficult for me to get past this stage. Am I on the right
> track? And more importantly, how could I learn how to actually implement
> this in smaller stages?
>
>
 You're on the right track, and you're almost there! You've already broken
down the problem into steps. You should now try to implement a function for
each step, and finally you should glue these functions together into a
final program.

a) Though you don't *have* to use it, csv.reader is really quite simple,
I'd recommend it. Try and write a function that takes a file name as
argument and returns a dictionary of the form { name: id, name: id } (i.e.
the names are the keys).

b) For this step, you first need a list of all names in file 2. You could
use csv.reader again or you could just parse it. Then, you use the
dictionary to look up the corresponding id. The end goal for this function
is to return a list of lists that looks much like the file you want to end
up with:

[[id, name],
 [id, name],
 [id, name]]

c) this step should now be easy. I'd again, recommend csv.writer, it makes
the process pretty simple. You just pass in the nested list from step (b)
and you're pretty much done.

For tips on the csv module, the list of examples is pretty helpful:
http://docs.python.org/py3k/library/csv.html#examples
If you need help constructing the lists and dictionaries, my tips would be
1) think one row at a time, 2) the for loop is your best friend, and 3)
nested lists usually means nested loops

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


Re: [Tutor] Reading a csv of coordinates, trying to write a csv of bearings.

2012-07-09 Thread Hugo Arts
On Mon, Jul 9, 2012 at 3:10 AM, Gregory Lund  wrote:

> I'm Not looking for an absolute solution, but perhaps some insight
> into some snippets of code, or
> suggestions of where I should seek out answers to this issue.
> Or where I've gone wrong below.
> NOTE: currently this 'code' below reads my file and writes a file, but
> what it's doing in the middle isn't what it's supposed to do (I know
> that!) I just modified what I had to at least read/write, now I need
> to add the atan2() stuff.
>
>
What is "this issue," exactly? I can not seem to find in your e-mail a
description of what problems you're having exactly. On another note, when
pasting any code beyond a simple single-function example, please consider
using a service such as http://pastebin.com/. Your code becomes very hard
to read once e-mail client formatting is done with it.

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


Re: [Tutor] using dynamic import statements

2012-07-09 Thread Hugo Arts
On Mon, Jul 9, 2012 at 3:10 AM, Chris Hare  wrote:

>
> Here is what I want to do:
>
> I have a bunch of modules to import. instead of duplicating a lot of code
> for each import, I want to do something like this:
>
> importList = [ "sys", "os", "imp", "stat", "re", "webbrowser", "Image",
>  "StringIO", "shutil", "datetime" ]
>
> for object in importList:
> try:
> if debug == "ON":
> print "Importing module %s" % (object)
> exec( "import  " + object)
> except ImportError as error:
> print "%s %s requires the Python %s library.  " % (
> appName,
>
> str(appVersion), object )
> print "An error occurred when attempting to load the
> library.  The error was '%s'." % ( error )
> exit()
>
> Everything "appears" to run okay, however, when the first piece of code
> that relies upon one of these imported modules is executed, I get an error:
>
> Traceback (most recent call last):
>   File "a.py", line 122, in 
> imp.load_module(object,fp,pathName,description)
>   File "./Modules/functions.py", line 133, in 
> def special_match(strg, search=re.compile(r'[^a-zA-Z0-9\.\
> \-\#\$\*\@\!\%\^\&]').search):
> NameError: name 're' is not defined
>
> Is is possible to do what I am trying to do, or am I doing something wrong?
>
>
 Yes, it is possible, but you are doing something wrong. Don't use exec()
for this, it's unnecessary. You can make this work with the exec function,
but the function you really want is called __import__(). It's documented
here: http://docs.python.org/library/functions.html#__import__

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