Re: [Tutor] question about importing threads
shawn bright wrote: great, saves me 15 lines. thanks You have 15 lines of imports? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
ok, i have started doing this with my 4000 + line file. So far its been working out. i have another question about it. i have two classes in my program that use a global object that is a socket connection. example: global my_sockobj serverhost = 'mehost.com' serverport = 9100 my_sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM) my_sockobj.connect((serverhost,serverport)) then i use my_socket.recv to get stuff from the socket in one class and my_socket.send to send stuff from another class. is there something tricky about passing this as a global object to different modules that would need to use it? Or does this go along with what you wrote a while back about having classes that depend on each other ? One runs as a thread, the other responds to gui input. thanks for any tips. shawn On 12/31/06, Alan Gauld [EMAIL PROTECTED] wrote: shawn bright [EMAIL PROTECTED] wrote Yes, the thing is getting to be a pain to deal with at this size, i am in-process of splitting out the classes into their own files. One thing to watch is that while its easy and tempting to create one file per class it's often better to keep dependant classes together. In other words if class A can only be used together with class B then it is often better to keep A and B in the same module. Anyone who needs B can import the module and anyone who needs A needs B too so it saves them having to import two modules. As in all things in programming a little bit of thought is often better than the first obvious strategy. Grady Booch described the above strategy by saying that the unit of reuse is the category (which in his OO notation was a set of related classes) and in Python that means the module. Regards, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
i have two classes in my program that use a global object that is a socket connection. ... code snipped is there something tricky about passing this as a global object to different modules that would need to use it? Whiler its possible to use a global in this way its usually better to avoid global objects in a reusable component since otherwise it might clash with another global that the reuser already has. Its much better to use a parameter which can be provided by the user of the classes. In this case the socklet becomesc a parameter. A good place to put this parameter would be the init method of both your classes, where they would store a reference to it as an internal attribute. (remember that in Python all attributes are references so if you pass the same socket to both constructors both classes will point at the same socket). This approach also allows the user of your classes to suvbstitute any socketlike object that they mauy have, even their own bespoke version if needed. That greatly increases the flexibility of your code. Or does this go along with what you wrote a while back about having classes that depend on each other ? If you really must use a shared global then I would strongly consider putting both classes, the global variable and an initialisation function all in a single module. If however tyou can parameterise things as described then you need to consider whether anyone would be able to (and want to) use either of the classes without the other. If you always need them as a pair they still should go in one module, otherwise put them in separate modules. One runs as a thread, the other responds to gui input. Does it respond to GUI input or just input? If it can be independant of the GUI (and you should really try hard to make it so) then its independant and best in its own module. The fact that the other runs in a thred is fairly irrelevant to this discussion, the real issue is whether it has hard coded dependencies on the other class. For example does it instantiate a copy within its methods? (in which case you must import the other module/class into this module) And more especially does it take an instance as a parameter of a method? (in which case the *re-user* must import the other module.) In the second case I'd say definitely put them in a single module, in the first case consider it, but it's not essential. I hope that makes sense, Alan G. On 12/31/06, Alan Gauld [EMAIL PROTECTED] wrote: shawn bright [EMAIL PROTECTED] wrote Yes, the thing is getting to be a pain to deal with at this size, i am in-process of splitting out the classes into their own files. One thing to watch is that while its easy and tempting to create one file per class it's often better to keep dependant classes together. In other words if class A can only be used together with class B then it is often better to keep A and B in the same module. Anyone who needs B can import the module and anyone who needs A needs B too so it saves them having to import two modules. As in all things in programming a little bit of thought is often better than the first obvious strategy. Grady Booch described the above strategy by saying that the unit of reuse is the category (which in his OO notation was a set of related classes) and in Python that means the module. Regards, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ New Yahoo! Mail is the ultimate force in competitive emailing. Find out more at the Yahoo! Mail Championships. Plus: play games and win prizes. http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about a list of lists
Thanks Kent, i am going with option A, the helper set, because i also need to count the occurances and this seems to be the easiest solution. thanks for your help. shawn On 1/28/07, Kent Johnson [EMAIL PROTECTED] wrote: shawn bright wrote: lo there all. i have a list of lists that i want to build, only if an item is not in the list already. kinda like this new_list = [] for item in lists: # item will look something like [var1, var2, var3] if item[0] in new_list ( only the first element of each list ) like new_list[0][0] basicly, i want to know if item[0] is one of the items[0] in my new_list whats a good pythonic way to do this? i mean, i have a couple of way to do this, but they are ugly. One way to do this is to keep a helper set that contains the first elements of each list. Something like new_list = [] firsts = set() for item in lists: if item[0] not in firsts: new_list.append(item) firsts.add(item[0] If you don't care about the order of the result, and if two lists have duplicate first items you are happy to use the first, then you could use a dict mapping first item to list: new_list = dict((item[0], item) for item in lists).values() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about a list of lists
shawn bright wrote: Thanks Kent, i am going with option A, the helper set, because i also need to count the occurances and this seems to be the easiest solution. If you need the number of unique items that is just the length of the final list. If you need the number of occurrences of each initial item then a dict mapping initial item to count (or maybe a list of lists) would be the way to go. Kent thanks for your help. shawn On 1/28/07, *Kent Johnson* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: shawn bright wrote: lo there all. i have a list of lists that i want to build, only if an item is not in the list already. kinda like this new_list = [] for item in lists: # item will look something like [var1, var2, var3] if item[0] in new_list ( only the first element of each list ) like new_list[0][0] basicly, i want to know if item[0] is one of the items[0] in my new_list whats a good pythonic way to do this? i mean, i have a couple of way to do this, but they are ugly. One way to do this is to keep a helper set that contains the first elements of each list. Something like new_list = [] firsts = set() for item in lists: if item[0] not in firsts: new_list.append(item) firsts.add(item[0] If you don't care about the order of the result, and if two lists have duplicate first items you are happy to use the first, then you could use a dict mapping first item to list: new_list = dict((item[0], item) for item in lists).values() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about a list of lists
lo there all. i have a list of lists that i want to build, only if an item is not in the list already. kinda like this new_list = [] for item in lists: # item will look something like [var1, var2, var3] if item[0] in new_list ( only the first element of each list ) like new_list[0][0] basicly, i want to know if item[0] is one of the items[0] in my new_list whats a good pythonic way to do this? i mean, i have a couple of way to do this, but they are ugly. shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about a list of lists
shawn bright [EMAIL PROTECTED] wrote new_list = [] for item in lists: # item will look something like [var1, var2, var3] if item[0] in new_list basicly, i want to know if item[0] is one of the items[0] in my new_list Your pseudo code is pretty much exactly right. What more are you looking for? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about a list of lists
shawn bright wrote: lo there all. i have a list of lists that i want to build, only if an item is not in the list already. kinda like this new_list = [] for item in lists: # item will look something like [var1, var2, var3] if item[0] in new_list ( only the first element of each list ) like new_list[0][0] basicly, i want to know if item[0] is one of the items[0] in my new_list whats a good pythonic way to do this? i mean, i have a couple of way to do this, but they are ugly. One way to do this is to keep a helper set that contains the first elements of each list. Something like new_list = [] firsts = set() for item in lists: if item[0] not in firsts: new_list.append(item) firsts.add(item[0] If you don't care about the order of the result, and if two lists have duplicate first items you are happy to use the first, then you could use a dict mapping first item to list: new_list = dict((item[0], item) for item in lists).values() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about *args and functions
lo there all, if i have a function that sometimes needs a value passed to it and sometimes not, is this where i use *args ? like this def some_function(req_var, req_var2, un_req_var): do some stuff return value how would i use this if sometimes i need to process un_req_var and sometimes not ? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about *args and functions
2007/1/26, shawn bright [EMAIL PROTECTED]: lo there all, if i have a function that sometimes needs a value passed to it and sometimes not, is this where i use *args ? No. *args is used if there are arguments that could occur more than once. like this def some_function(req_var, req_var2, un_req_var): do some stuff return value how would i use this if sometimes i need to process un_req_var and sometimes not ? Use: def some_function(req_var, req_var2, un_req_var = None): do some stuff return value Now, the function can be called both with and without un_req_var, and if it is called without un_req_var, within the function body un_req_var is considered to be None. -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about *args and functions
shawn bright wrote: lo there all, if i have a function that sometimes needs a value passed to it and sometimes not, is this where i use *args ? No, use an optional argument. like this def some_function(req_var, req_var2, un_req_var): do some stuff return value how would i use this if sometimes i need to process un_req_var and sometimes not ? def some_function(req_var, req_var2, un_req_var=None): do some stuff return value Now the caller can write some_function(1, 2) or some_function(1, 2, 3). You can distinguish the two by checking for 'un_req_var is None'. If None is a legitimate value for un_req_var then you need to pick some other sentinal value. If there is no built-in value that works, create your own: missing = object() def some_function(req_var, req_var2, un_req_var=missing): Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about *args and functions
Greetings, You could default it to None and check in your script to see if it has changed. def some_function(req_var, req_var2, un_req_var=None): if un_req_var != None: dosomething else: dosomethingelse Wesley Brooks. On 26/01/07, shawn bright [EMAIL PROTECTED] wrote: lo there all, if i have a function that sometimes needs a value passed to it and sometimes not, is this where i use *args ? like this def some_function(req_var, req_var2, un_req_var): do some stuff return value how would i use this if sometimes i need to process un_req_var and sometimes not ? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about *args and functions
Great, gents, thanks. tried it out and is working fine, this will clean up a lot of stuff for me. thanks for your help ! shawn On 1/26/07, Wesley Brooks [EMAIL PROTECTED] wrote: Greetings, You could default it to None and check in your script to see if it has changed. def some_function(req_var, req_var2, un_req_var=None): if un_req_var != None: dosomething else: dosomethingelse Wesley Brooks. On 26/01/07, shawn bright [EMAIL PROTECTED] wrote: lo there all, if i have a function that sometimes needs a value passed to it and sometimes not, is this where i use *args ? like this def some_function(req_var, req_var2, un_req_var): do some stuff return value how would i use this if sometimes i need to process un_req_var and sometimes not ? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about structuring my pygtk program
Hi Everybody, I have a question about structuring first pygtk program now that I have the basics working, I am moving to the next step of organizing my program so it doesn't turn into spaghetti code. Right now, what I'm doing is if a component of the GUI is used in more than one spot, I make that into a separate little function returning a GUI fragment that I can call several times throughout the program. I have been doing this type of non-redundant code in a non-GUI environment for many years, and it's worked well. Also, I read about this technique from the Pragmatic Programmer - having one section of code that does a specific task - instead of having it in multiple locations. Does this translate to the GUI environment? If so, is there an easy of accessing the different input boxes easily? If you need a code exxample, just ask. Thanks, -Tino ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about object oriented programming and inheritance using datetime module
On Mon, 15 Jan 2007, Kent Johnson wrote: [EMAIL PROTECTED] wrote: My class inherits from the date class, but I have to type 'from datetime import date' before I can initialize the class definition. Is there some way to avoid this ? No, and really there is no reason to want to avoid this. You have to import any external module that you want to use directly. Imports are very common in Python code and there is no reason not to use them. I had a similar issue when I started Python, so I think I know what tpc may be after. My thought was that I did not want to do the import if the class was not actually going to be used. I was really thinking about it the wrong way, though. Really, I would not want to do the import unless the class was going to be *defined* for use. The right approach here is to put the class into a module, and the import statement into the new module as well. Then, a program that needs to use the class imports the module; and that module, only if it is imported, imports the classes on which it depends. In this case, tpc's class might be defined in a MyDateStuff.py module, which contains: import datetime class age_calculator(datetime.date): etc. Then, when he imports MyDateStuff, it imports datetime and defines age_calculator. I second Kent's concerns over this, though. It sounds like age_calculator is really a method that uses datetime.date; not a subclass of datetime.date. The question you should ask is: will an age_calculator object actually also be a date object? If so, subclassing makes sense. Otherwise, think of using a method. Put another way, you should think of a statement like class age_calculator(datetime.date): as meaning define a new class named age_calculator; an age_calculator object is a type of date object. An example is if you wanted to create a birthdate class, which was just like a regular date, but also included the birthstone that corresponded to the date. We could create a birthdate module that included a Birthdate class: ### import datetime class Birthdate(datetime.date): def __init__(self, year, month, day): stones = [Garnet, Amethyst, Aquamarine, Diamond, Emerald, Perl, Ruby, Python, Sapphire, Opal, Topaz, Turquoise] self.birthstone = stones[month-1] ### We could create a Birthdate object like this: import birthdate z = birthdate.Birthdate(1971, 7, 12) Note, it has the birthstone for July: z.birthstone 'Ruby' It also has inherited the other attributes and methods of the standard datetime.date class on which it was based: z.isoformat() '1971-07-12' Because a birthdate is after all, just a particular kind of date; and the Birthdate class is just a particular kind of date class. But in your case, with a name like age_calculator, it doesn't sound like an age_calculator is a kind of date. It sounds like a thing that calculates ages. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about object oriented programming and inheritance using datetime module
Terry Carroll wrote: An example is if you wanted to create a birthdate class, which was just like a regular date, but also included the birthstone that corresponded to the date. We could create a birthdate module that included a Birthdate class: ### import datetime class Birthdate(datetime.date): def __init__(self, year, month, day): stones = [Garnet, Amethyst, Aquamarine, Diamond, Emerald, Perl, Ruby, Python, Sapphire, Opal, Topaz, Turquoise] self.birthstone = stones[month-1] I think you are missing the line datetime.date.__init__(self, year, month, day) somewhere in here. I am very surprised that this works, my understanding was that datetime.date was immutable and required overriding __new__() rather than __init__(). But it does work... Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about object oriented programming and inheritance using datetime module
hey guys, I've been experimenting with Python's datetime module, and I created a function that, given a person's birthdate, calculates how old that person is. Now I want to create a class called age_calculator that does much the same thing. My class inherits from the date class, but I have to type 'from datetime import date' before I can initialize the class definition. Is there some way to avoid this ? Also, once I type the import statement and initialize my class definition, I can create an instance of age_calculator. The instance of age_calculator stores the given birthdate, and gives me a infinite loop traceback when I call self.today(). If I don't inherit from date, I would need to put the import statement somewhere inside a method, and I don't recall ever seeing that done. Part of me feels like that's not as elegant as defining an age_calculator class that inherits from datetime.date, but I'm not sure how to do this. For what it's worth, here's my pseudocode (that inherits from date module) and working code (that does not inherit from date module): from datetime import date class age_calculator(date): def __init__(self, year, month, day): time_delta = self.today() - self number_of_years = time_delta.days / 365 return number_of_years class age_calculator: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def calculate_age(self): from datetime import date birth_date = date(self.year, self.month, self.day) date_today = date.today() time_delta = date_today - birth_date number_of_years = time_delta.days / 365 return number_of_years age_calculator(1964, 9, 27).calculate_age() 42 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about object oriented programming and inheritance using datetime module
[EMAIL PROTECTED] wrote: hey guys, I've been experimenting with Python's datetime module, and I created a function that, given a person's birthdate, calculates how old that person is. Now I want to create a class called age_calculator that does much the same thing. My class inherits from the date class, but I have to type 'from datetime import date' before I can initialize the class definition. Is there some way to avoid this ? No. In order to use class inheritance syntax, class some_class(some_object): some_object must be defined. Otherwise you'll get a variable not defined error. You could make your own class called 'date' and inherit from that, but what would be the point of that? Also, once I type the import statement and initialize my class definition, I can create an instance of age_calculator. The instance of age_calculator stores the given birthdate, and gives me a infinite loop traceback when I call self.today(). If I don't inherit from date, I would need to put the import statement somewhere inside a method, and I don't recall ever seeing that done. What makes you think you'd have to import within a method? Import datetime.date into the global namespace. That's perfectly alright. Especially since your class depends on it being available. Part of me feels like that's not as elegant as defining an age_calculator class that inherits from datetime.date, but I'm not sure how to do this. For what it's worth, here's my pseudocode (that inherits from date module) and working code (that does not inherit from date module): The way you'd go about doing this is to make an extra function that is unique to your inherited class (for example, calculate_age). from datetime import date class age_calculator(date): def __init__(self, year, month, day): time_delta = self.today() - self number_of_years = time_delta.days / 365 return number_of_years This init method is overriding the init of the inherited date class. The reason today() doesn't work is probably because of this. class age_calculator: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def calculate_age(self): from datetime import date birth_date = date( self.year, self.month, self.day) date_today = date.today() time_delta = date_today - birth_date number_of_years = time_delta.days / 365 return number_of_years Just move the import outside of the class. from datetime import date class age_calculator: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def calculate_age(self): birth_date = date( self.year, self.month, self.day) date_today = date.today() time_delta = date_today - birth_date number_of_years = time_delta.days / 365 return number_of_years I don't think you really want to inherit from date. HTH, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about object oriented programming and inheritance using datetime module
[EMAIL PROTECTED] wrote: hey guys, I've been experimenting with Python's datetime module, and I created a function that, given a person's birthdate, calculates how old that person is. Now I want to create a class called age_calculator that does much the same thing. Why? You have a perfectly good function that does what you want, there is no need to turn it into a class. One of the strengths of Python is that not everything needs to be a class. My class inherits from the date class, but I have to type 'from datetime import date' before I can initialize the class definition. Is there some way to avoid this ? No, and really there is no reason to want to avoid this. You have to import any external module that you want to use directly. Imports are very common in Python code and there is no reason not to use them. Inheriting from date isn't a very good idea. You should inherit from date if your class will be a specialized kind of date. I guess you could think of your class as adding an age() method to date, but you are thinking of it as a calculator. Also date objects are immutable which makes it harder to create a subclass of date. (You have to override __new__() rather than __init__(), but explaining that will probably just confuse you at this point.) There are a few things in your code that are a bit confused - you need to call the base class __init__() in your __init__() method, and __init__() does not return a value. You should probably read up a bit more on classes in Python, either a book or one of the on-line tutorials. Also, once I type the import statement and initialize my class definition, I can create an instance of age_calculator. The instance of age_calculator stores the given birthdate, and gives me a infinite loop traceback when I call self.today(). If I don't inherit from date, I would need to put the import statement somewhere inside a method, and I don't recall ever seeing that done. It is OK to put an import inside a function or method, but why do you think you need to do this? Part of me feels like that's not as elegant as defining an age_calculator class that inherits from datetime.date, but I'm not sure how to do this. For what it's worth, here's my pseudocode (that inherits from date module) and working code (that does not inherit from date module): from datetime import date class age_calculator(date): def __init__(self, year, month, day): time_delta = self.today() - self number_of_years = time_delta.days / 365 return number_of_years I'm not sure why this gives an infinite loop (not even sure what an infinite loop traceback is), but you have not initialized the base class so the year, month, day parameters are not used at all. class age_calculator: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def calculate_age(self): from datetime import date birth_date = date( self.year, self.month, self.day) date_today = date.today() time_delta = date_today - birth_date number_of_years = time_delta.days / 365 return number_of_years This is better, but compare it to your functional version and you should see why the function is preferred. Kent age_calculator(1964, 9, 27).calculate_age() 42 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question on joining out of order dictionary elements
Hi everyone, I have a quick quick question joining out of order dictionary values. For example: I created an empty config={} Added some key/value pairs config[test1]=elem1 config[test2]=elem2 config[test3]=elem3 etc Dumped the values and joined them at the same time. print \\.join(config.values()) elem1\elem3\elem2 This is fine but it doesn't entirely solve the issue. Only some of the key/value pairs in the dictionary are needed so a dump of all values does not work. Also, the order in which the values are joined is important so walking through and joining all values does not work either. The simplest way would be to do something like: print \\.join((config[val2],config[val1],config[val3])) elem2\elem1\elem3 or print %s\\%s\\%s % (config[val2],config[val1],config[val3]) elem2\elem1\elem3 but this seems somehow uneligent. Are there a more efficient/compact ways of doing this kind of operation or is this it? The key/value pairs in these examples are contrived for purposes of this discussion but the end goal is to piece together server and directory path information for use with pysvn. I have a Perl programmer who is learning Python and he is griping that this kind of operation is far simpler in Perl. To print or to retain individual values from a list,it has to be written in the form of config={'test1':'elem1','test2':'elem2','test3':'elem3'} config['test4'] = 'elem4' print config.values() print config['test1']- To get individual values from a list If we want to retrieve all the values or say 2 from 4 its not possible to put in a while loop and get that as a list only takes one argument at a time better way is to extract individually and respective keys could not be obtained if corresponding values are given. -- Vanam ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on joining out of order dictionary elements
2007/1/11, raghu raghu [EMAIL PROTECTED]: print \\.join((config[val2],config[val1],config[val3])) elem2\elem1\elem3 or print %s\\%s\\%s % (config[val2],config[val1],config[val3]) elem2\elem1\elem3 but this seems somehow uneligent. Are there a more efficient/compact ways of doing this kind of operation or is this it? Maybe you like: print \\.join([config[val] for val in [val2,val1,val3]]) -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on joining out of order dictionary elements
I like this solution. Thanks everyone for all of the suggestions. On 1/11/07, Andre Engels [EMAIL PROTECTED] wrote: 2007/1/11, raghu raghu [EMAIL PROTECTED]: print \\.join((config[val2] ,config[val1],config[val3])) elem2\elem1\elem3 or print %s\\%s\\%s % (config[val2],config[val1],config[val3]) elem2\elem1\elem3 but this seems somehow uneligent. Are there a more efficient/compact ways of doing this kind of operation or is this it? Maybe you like: print \\.join([config[val] for val in [val2,val1,val3]]) -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Thank you, Andrew Robert Senior MQ Engineer Information Technologies Massachusetts Financial Services Phone: 617-954-5882 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on joining out of order dictionary elements
raghu raghu wrote: [snip original message] To print or to retain individual values from a list,it has to be written in the form of config={'test1':'elem1','test2':'elem2','test3':'elem3'} config['test4'] = 'elem4' print config.values() print config['test1']- To get individual values from a list If we want to retrieve all the values or say 2 from 4 its not possible to put in a while loop and get that as a list only takes one argument at a time better way is to extract individually and respective keys could not be obtained if corresponding values are given. Hello, raghu - Please don't reply like this. It breaks threading. You should have a Re: in the title bar, and the quoted text should have before it. If you reply like you did, it creates a new thread in Thunderbird. I believe the 'reply all' button has some kind of magic that tells mail clients it's a reply to another message. In addition, please don't use bolding. If you reply normally, it will be clear what text is yours and what is from the original author. Bolding text just makes it harder to read. Thanks, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question on joining out of order dictionary elements
Hi everyone, I have a quick quick question joining out of order dictionary values. For example: I created an empty config={} Added some key/value pairs config[test1]=elem1 config[test2]=elem2 config[test3]=elem3 etc Dumped the values and joined them at the same time. print \\.join(config.values()) elem1\elem3\elem2 This is fine but it doesn't entirely solve the issue. Only some of the key/value pairs in the dictionary are needed so a dump of all values does not work. Also, the order in which the values are joined is important so walking through and joining all values does not work either. The simplest way would be to do something like: print \\.join((config[val2],config[val1],config[val3])) elem2\elem1\elem3 or print %s\\%s\\%s % (config[val2],config[val1],config[val3]) elem2\elem1\elem3 but this seems somehow uneligent. Are there a more efficient/compact ways of doing this kind of operation or is this it? The key/value pairs in these examples are contrived for purposes of this discussion but the end goal is to piece together server and directory path information for use with pysvn. I have a Perl programmer who is learning Python and he is griping that this kind of operation is far simpler in Perl. -- Thank you, Andrew Robert Senior MQ Engineer Information Technologies Massachusetts Financial Services Phone: 617-954-5882 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on joining out of order dictionary elements
On 11/01/07, Andrew Robert [EMAIL PROTECTED] wrote: Only some of the key/value pairs in the dictionary are needed so a dump of all values does not work. Also, the order in which the values are joined is important so walking through and joining all values does not work either. Well, a dictionary is by definition unordered, so you will need to tell python which elements you want, and in which order. I would do something like this: config = {} # insert code here to set the values of config keysToDump = ['test1', 'test2', 'test3'] output = '\\'.join(config[k] for k in keysToDump) (note that, if you are using python2.3 or earlier, you will need to write that last line as: output = '\\'.join([config[k] for k in keysToDump]) ) HTH! -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about __name__ global variable (Was: Tutor Digest, Vol 35, Issue 27)
raghu raghu wrote: i have a clarification regarding built in function,in some scripts it is being used and it is give n: if _name_ == '_main_' why this is being used in the scripts? The global variable __name__ is equal to '__main__' when the python script is run. If the script is imported, __name__ is something other than '__main__' (not sure what.) So by checking if __name__ == '__main__' we can ensure that our code can work both as a standalone script and as a module. For example: #test-script.py import random def someFunction(a): return a * random.randrange(100) if __name__ == __main__: print The number 42 passed to someFunction is: + someFunction(42) #- If we want to use the function someFunction from test-script.py in a different file, the 'main' part won't be run. # import test-script print The number 3 passed to someFunction is: + someFunction(3) #- if the 'if __name__ == '__main__' ' test weren't in the original test-script.py, the 42 version of the print statement would be run whenever someone imported it. HTH, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about pydev
hey there gents, i was wondering if anyone uses pydev ? its a plugin for eclipse. Has lots of cool stuffs, but i don't like the way it does code snippets, when i paste one that is kinda long, it messes up the indentation. anyone know a way around this ? i have posted this question on the pydev sourceforge list ( about 2 weeks ago ) and have not heard anything, so thought i would ask the folk most likely to be using it. thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about __name__ global variable (Was: Tutor Digest, Vol 35, Issue 27)
The global variable __name__ is equal to '__main__' when the python script is run. If the script is imported, __name__ is something other than '__main__' (not sure what.) it will be the name of your module. so for foo.py, if you execute it (as a script), __name__ == '__main__', but if you 'import foo', __name__ == 'foo'. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Core Python Programming, Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about ConfigParser
Reply to Dave Kuhlman [EMAIL PROTECTED] 07-01-06 15:26: It's sort of hidden, but note the restriction to string values in the docs on the set method: set(section, option, value) If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. While it is possible to use RawConfigParser (or ConfigParser with raw parameters set to true) for internal storage of non-string values, full functionality (including interpolation and output to files) can only be achieved using string values. New in version 1.6. A ... I was spending all my time reading the docs for 'items' ;-) Thanks jem ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about ConfigParser
I'm trying to use ConfigParser for the first time and I'm missing something. I have this code import ConfigParser import datetime conf = ConfigParser.ConfigParser() conf.add_section('general') conf.set( 'general', 'revision', 0 ) conf.set( 'general', 'date', datetime.datetime.now().strftime(%Y-%m-%d) ) conf.set( 'general', 'currentsetname', '' ) conf.set( 'general', 'incrementalcount', 0 ) conf.add_section( Hello world ) conf.set( Hello world, 'apa', 3298 ) print conf.sections() print conf.items('general') #for debug_repos in conf.sections(): # print debug_repos #, conf.items( debug_repos ) When I run this I get the following result ['Hello world', 'general'] Traceback (most recent call last): File backup.py, line 15, in module print conf.items('general') File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py, line 557, in items for option in options] File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py, line 565, in _interpolate if %( in value: TypeError: argument of type 'int' is not iterable What am I missing with the items call? jem ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about ConfigParser
On Sat, Jan 06, 2007 at 10:40:27PM +0100, Jan Erik Mostr??m wrote: I'm trying to use ConfigParser for the first time and I'm missing something. I have this code import ConfigParser import datetime conf = ConfigParser.ConfigParser() conf.add_section('general') conf.set( 'general', 'revision', 0 ) conf.set( 'general', 'date', datetime.datetime.now().strftime(%Y-%m-%d) ) conf.set( 'general', 'currentsetname', '' ) conf.set( 'general', 'incrementalcount', 0 ) conf.add_section( Hello world ) conf.set( Hello world, 'apa', 3298 ) print conf.sections() print conf.items('general') #for debug_repos in conf.sections(): # print debug_repos #, conf.items( debug_repos ) When I run this I get the following result ['Hello world', 'general'] Traceback (most recent call last): File backup.py, line 15, in module print conf.items('general') File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py, line 557, in items for option in options] File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py, line 565, in _interpolate if %( in value: TypeError: argument of type 'int' is not iterable What am I missing with the items call? Here is a clue -- If you write out your configuration to a file with something like: conf.write(sys.stdout) and store it in a file. Then, if you read it in, all seems to work well. For example, the following function: def test2(): conf = ConfigParser.ConfigParser() conf.read('test1.conf') print 'options -- general:', conf.options('general') opt1 = conf.get('general', 'date') print 'opt1:', opt1 print conf.items('general') executes without error. Can you guess why? Note that in your original code, the default values for some of your options have type int. If you change those to strings, then the error goes away. For example, change: conf.set( 'general', 'revision', 0 ) to: conf.set( 'general', 'revision', 0 ) Writing it to a file does this conversion and hides the error. It's sort of hidden, but note the restriction to string values in the docs on the set method: set(section, option, value) If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. While it is possible to use RawConfigParser (or ConfigParser with raw parameters set to true) for internal storage of non-string values, full functionality (including interpolation and output to files) can only be achieved using string values. New in version 1.6. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question regarding parsing HTML with BeautifulSoup
Hi, Wow, thats much more elegant than the idea I thought of. Thank you very much Kent! Marshall On 1/3/07, Kent Johnson [EMAIL PROTECTED] wrote: Shuai Jiang (Runiteking1) wrote: Hello, I'm working on a program that need to parse a financial document on the internet using BeautifulSoup. Because of the nature of the information, it is all grouped as a table. I needed to get 3 types of info and have succeeded quite well using BeautifulSoup, but encountered problems on the third one. My question is that is there any easy way to parse an HTML tables column easily using BeautifulSoup. I copied the table here and I need to extract the EPS. The numbers are every sixth one from the tr tag ex 2.27, 1.86, 1.61... Here is one way, found with a little experimenting at the command prompt: In [1]: data = '''table id=INCS style=width:580px class=f10y cellspacing=0 snip the rest of your data ...: /table''' In [3]: from BeautifulSoup import BeautifulSoup as BS In [4]: soup=BS(data) In [11]: for tr in soup.table.findAll('tr'): : print tr.contents[11].string : : EPS 2.27 1.86 1.61 1.27 1.18 0.84 0.73 0.46 0.2 0.0 Kent -- I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals. Sir Winston Churchill ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
Thanks, Alan. Yes, the thing is getting to be a pain to deal with at this size, i am in-process of splitting out the classes into their own files. Thanks for your help. shawn On 12/30/06, Alan Gauld [EMAIL PROTECTED] wrote: shawn bright [EMAIL PROTECTED] wrote i testing this right away. This long a .py script is becomming a headache and i think it will be easier by far if it is pulled apart somewhat. As a general rule of thumb, any Python script (or any programming language file for that matter!) that gets longer than 4 or 5 hundred lines should be looked at closely in terms of splitting it into modules. There are a few (very few) times where I've seen a thousand line file that was justified, but nearly any time you get beyond 500 lines you should be splitting things up - especially in high level languages like Python where the methods/functions tend to be short anyway. FWIW A quick check of the Python standard library shows the average file size there to be: 459 lines(*) And that's pretty high IMHO! There are 19 files over a thousand lines and the biggest file is over 3000 lines... which seems way too big to me! But that's out of 188 files... (*) Cygwin; Python 2.4 In case you want to repeat for your version I used: libs = [len(open(f).readlines()) for f in glob('*.py')] print sum(libs)/len(libs) print max(libs) print len([s for s in libs if s1000]) Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
shawn bright [EMAIL PROTECTED] wrote Yes, the thing is getting to be a pain to deal with at this size, i am in-process of splitting out the classes into their own files. One thing to watch is that while its easy and tempting to create one file per class it's often better to keep dependant classes together. In other words if class A can only be used together with class B then it is often better to keep A and B in the same module. Anyone who needs B can import the module and anyone who needs A needs B too so it saves them having to import two modules. As in all things in programming a little bit of thought is often better than the first obvious strategy. Grady Booch described the above strategy by saying that the unit of reuse is the category (which in his OO notation was a set of related classes) and in Python that means the module. Regards, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about importing threads
Hello there all. i have an app that has grown to about 4000 lines. It uses 6 threads and a GTK2 GUI. i was wondering if i could split it into seperate files that i could import. Each thread is a class. i did not think that this would be a problem, but some of the threads pass information to views and buffers. If i had a thread outside of the main file, could i pass a gtk object to it so that it could write to it when it needed too? and one last thing. If i did this, would i be able to only import the class when i started the thread, and then re-import it if i started the thread later . If so, this would allow me to work on a thread without having to restart the main program, and i could let the other threads keep running. As i find bugs, i could squash them without loosing any functionality of the other threads. Then if i wanted to stop or restart a thread by clicking a button, i could just re-import the class. is this ok ? thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
shawn bright wrote: Hello there all. i have an app that has grown to about 4000 lines. It uses 6 threads and a GTK2 GUI. i was wondering if i could split it into seperate files that i could import. Each thread is a class. That should be fine. i did not think that this would be a problem, but some of the threads pass information to views and buffers. How do the threads find out about the views and buffers? If they are global objects then you will have a problem. If they are passed to the threads as parameters then it should be fine. If i had a thread outside of the main file, could i pass a gtk object to it so that it could write to it when it needed too? Yes. and one last thing. If i did this, would i be able to only import the class when i started the thread, and then re-import it if i started the thread later . If so, this would allow me to work on a thread without having to restart the main program, and i could let the other threads keep running. As i find bugs, i could squash them without loosing any functionality of the other threads. Then if i wanted to stop or restart a thread by clicking a button, i could just re-import the class. is this ok ? You can use reload() to update a module that has been changed. You will also have to recreate any objects that were created from classes in the module so they become instances of the modified module. You might be interested in this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Kent thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
Kent, Thanks. this is great. Yes, when i start the thread, i also pass the gtk object to it. kinda like this. serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view) serial_1.start() so i am wanting to change that, but i do not exactly know how to stop a thread once i have it running, so that i could start another one. anyway, thanks for the link and the info, i am going to get started on testing this right away. This long a .py script is becomming a headache and i think it will be easier by far if it is pulled apart somewhat. thanks again shawn On 12/30/06, Kent Johnson [EMAIL PROTECTED] wrote: shawn bright wrote: Hello there all. i have an app that has grown to about 4000 lines. It uses 6 threads and a GTK2 GUI. i was wondering if i could split it into seperate files that i could import. Each thread is a class. That should be fine. i did not think that this would be a problem, but some of the threads pass information to views and buffers. How do the threads find out about the views and buffers? If they are global objects then you will have a problem. If they are passed to the threads as parameters then it should be fine. If i had a thread outside of the main file, could i pass a gtk object to it so that it could write to it when it needed too? Yes. and one last thing. If i did this, would i be able to only import the class when i started the thread, and then re-import it if i started the thread later . If so, this would allow me to work on a thread without having to restart the main program, and i could let the other threads keep running. As i find bugs, i could squash them without loosing any functionality of the other threads. Then if i wanted to stop or restart a thread by clicking a button, i could just re-import the class. is this ok ? You can use reload() to update a module that has been changed. You will also have to recreate any objects that were created from classes in the module so they become instances of the modified module. You might be interested in this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Kent thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
shawn bright wrote: Kent, Thanks. this is great. Yes, when i start the thread, i also pass the gtk object to it. kinda like this. serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view) serial_1.start() so i am wanting to change that, but i do not exactly know how to stop a thread once i have it running, so that i could start another one. The usual way to stop a thread is to set a flag that the thread checks. Here is an example using a threading.Event as a flag: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 anyway, thanks for the link and the info, i am going to get started on testing this right away. This long a .py script is becomming a headache and i think it will be easier by far if it is pulled apart somewhat. Yes, 4000 lines is pretty long for one file IMO. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
great help, and great link, thanks again. shawn On 12/30/06, Kent Johnson [EMAIL PROTECTED] wrote: shawn bright wrote: Kent, Thanks. this is great. Yes, when i start the thread, i also pass the gtk object to it. kinda like this. serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view) serial_1.start() so i am wanting to change that, but i do not exactly know how to stop a thread once i have it running, so that i could start another one. The usual way to stop a thread is to set a flag that the thread checks. Here is an example using a threading.Event as a flag: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 anyway, thanks for the link and the info, i am going to get started on testing this right away. This long a .py script is becomming a headache and i think it will be easier by far if it is pulled apart somewhat. Yes, 4000 lines is pretty long for one file IMO. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about importing threads
shawn bright [EMAIL PROTECTED] wrote i testing this right away. This long a .py script is becomming a headache and i think it will be easier by far if it is pulled apart somewhat. As a general rule of thumb, any Python script (or any programming language file for that matter!) that gets longer than 4 or 5 hundred lines should be looked at closely in terms of splitting it into modules. There are a few (very few) times where I've seen a thousand line file that was justified, but nearly any time you get beyond 500 lines you should be splitting things up - especially in high level languages like Python where the methods/functions tend to be short anyway. FWIW A quick check of the Python standard library shows the average file size there to be: 459 lines(*) And that's pretty high IMHO! There are 19 files over a thousand lines and the biggest file is over 3000 lines... which seems way too big to me! But that's out of 188 files... (*) Cygwin; Python 2.4 In case you want to repeat for your version I used: libs = [len(open(f).readlines()) for f in glob('*.py')] print sum(libs)/len(libs) print max(libs) print len([s for s in libs if s1000]) Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about exception handling
Hi Folks, Is it possible to catch exception raised in module A to be caught in module B. If yes, then please let me know how to do it. TIA. Regards, Asrarahmed Kadri -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about exception handling
On 17/12/06, Asrarahmed Kadri [EMAIL PROTECTED] wrote: Hi Folks, Is it possible to catch exception raised in module A to be caught in module B. If yes, then please let me know how to do it. You can easily test this yourself. First right a quick module, something like this will do: def exception_test(): raise Exception then start an interpreter and do the following import your_module try: ... your_module.exception_test() ... except: ... print Caught it! ... HTH, Adam ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about HORIZONTAL BAR CHART.....
Asrarahmed Kadri wrote: As far as I understand, I need to design an algorithm which computes the padding between each bar (space between each bar) and the length of each bar ( remember that this is a HORIZONTAL BAR CHART). I think what you want to design is an algorithm that computes the HEIGHT of each bar (as it's a HORIZONTAL bar chart) because the vertical padding, (The space between each bar) is a fixed number, like 20 pixels. At least that's what i would do. This height is dependent upon the number of data sets you have. For the width of the bars (remember this is a horizontal bar chart, so the heights of the bars will all be the same, but the widths will be different) you will want to set it up so that the largest data value is set to the widest bar, and the rest are percentages of this width. I hope that helps. -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about HORIZONTAL BAR CHART.....
As far as I understand, I need to design an algorithm which computes the padding between each bar (space between each bar) and the length of each bar ( remember that this is a HORIZONTAL BAR CHART). I am trying to understand your email. ( Please bear with my slow comprehension ) Regards, Asrarahmed Kadri On 11/24/06, Luke Paireepinart [EMAIL PROTECTED] wrote: Asrarahmed Kadri wrote: Hi Folks, I am constructing a bar-chart using Tkinter. The function takes a list 'data' and draws horizontal bar for each value. Now what I want is the the canvas widget should be able to handle variable number of data-items. I cannot figure out how to do that, because I have hard coded the lengths of X and Y axes. I want to make the entire function a lot more flexible so that it determines the length of both the axes on the basis of data supplied to it. #disclaimer Note: I didn't realize you said horizontal bar charts. This does vertical bar charts. It should be trivial to change this. Sorry for not reading your post more carefully to begin with. #for width data = [1,5,6,7,8,3,2,9] target_width = 600 padding = 10 num_of_data_items = len(data) individual_width =( target_width-(padding*(num_of_data_items-1)))/num_of_data_items individual_width 66 individual_width*num_of_data_items 528 padding* (len(data)-1) 70 528 + 70 598 #for height target_height = 600 maxval = max(yvals) for item in yvals: print int((float(item)/maxval) * target_height) 66 333 400 466 533 200 133 600 Did you honestly try to think this through before posting? It's a very simple concept. Not trying to be mean, just frank. I think you could've done this on your own if you had tried. Good luck with your bar charts. :) When you ask a question such as this I cannot figure out how to do that, because I have hard coded the lengths of X and Y axes. I want to make the entire function a lot more flexible so that it determines the length of both the axes on the basis of data supplied to it. The way you should be reasoning is this: I have hardcoded the lengths of the x and y axes. I need to change this for my function to operate how I want it to. How do I change it? 1) I have the data set already, so how do i figure out the width? (or height, if you're doing horizontal bar graphs) Well, I can make the following distinctions: - I have a target width (the width of the canvas) that they must all fit within. - all bars will be the same width - there should be some distance between each bar. - this distance should be the same no matter how many data elements there are, IE fixed. - so if I have a fixed width between variable amounts of data, how would I design an algorithm to perform this for me on any arbitrary data set? 2) How do I figure out the height of the data sets? (or width, if you're doing horizontal bar graphs) The following distinctions can be made: - I have a target height that they all must fit within (the height of the canvas) - Only the maximum value should be the full height of the canvas. - the others should be less than this height, depending NOT on their ratio to the height of the maximum bar, but on their ratio to the data that generated this. -- what do we use for ratios? Fractions! HTH, -Luke -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about __init__ in a class
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of shawn bright Sent: Monday, November 13, 2006 11:45 AM To: tutor-python Subject: [Tutor] question about __init__ in a class Hello there all. i have a class that i need to load some class variables depending on what is passed to the class, it would either be set up using one variable or another. The values for the class variables would be loaded from a database. But how it is looked up depends on how its called. Like this: class Sensor_Object(object): def __init__(self, id, monitor): if id: self.id = id load values from the database value1 = somevalue value2 = someOthervalue else: self.monitor = monitor get some values from database value1 = somevalue value2 = someothervalue now i could call it like this: new_monitor = sensor.Sensor('', 'XJ191') or new_monitor = sensor.Sensor('3433', '') to load based on the other variable. i think that this would work, but i was thinking that there must be a cleaner way to do it. any suggestions ? sk I don't know if it's cleaner, but it might be easier to read if you use default named arguments. def __init__(self, id = None, monitor = None): Calling it new_monitor = sensor.Sensor(monitor = 'XJ191') new_monitor = sensor.Sensor(id = '3433') Check to make sure one or the other arguments is supplied. Otherwise throw an exception. Maybe there'll be some better ideas from other posters. Mike - NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about __init__ in a class
Thats a lot better, thanks, will use it like that.-shawnOn 11/13/06, Mike Hansen [EMAIL PROTECTED] wrote: -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED]] On Behalf Of shawn bright Sent: Monday, November 13, 2006 11:45 AM To: tutor-python Subject: [Tutor] question about __init__ in a class Hello there all. i have a class that i need to load some class variables depending on what is passed to the class, it would either be set up using one variable or another. The values for the class variables would be loaded from a database. But how it is looked up depends on how its called. Like this: class Sensor_Object(object): def __init__(self, id, monitor): if id:self.id = idload values from the databasevalue1 = somevaluevalue2 = someOthervalue else: self.monitor = monitorget some values from databasevalue1 = somevaluevalue2 = someothervalue now i could call it like this: new_monitor = sensor.Sensor('', 'XJ191') or new_monitor = sensor.Sensor('3433', '') to load based on the other variable. i think that this would work, but i was thinking that there must be a cleaner way to do it. any suggestions ? skI don't know if it's cleaner, but it might be easier to read if you usedefault named arguments.def __init__(self, id = None, monitor = None): Calling itnew_monitor = sensor.Sensor(monitor = 'XJ191')new_monitor = sensor.Sensor(id = '3433')Check to make sure one or the other arguments is supplied. Otherwisethrow an exception.Maybe there'll be some better ideas from other posters. Mike-NOTICE:This e-mail transmission and any documents or files attached toit contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law.Any dissemination, distribution, or copying of this communication is strictly prohibited.Please notify the sender immediately if you are not the intended recipient. FGNS___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about __init__ in a class
Mike Hansen wrote: -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of shawn bright Sent: Monday, November 13, 2006 11:45 AM To: tutor-python Subject: [Tutor] question about __init__ in a class Hello there all. i have a class that i need to load some class variables depending on what is passed to the class, it would either be set up using one variable or another. I don't know if it's cleaner, but it might be easier to read if you use default named arguments. def __init__(self, id = None, monitor = None): Calling it new_monitor = sensor.Sensor(monitor = 'XJ191') new_monitor = sensor.Sensor(id = '3433') Check to make sure one or the other arguments is supplied. Otherwise throw an exception. Maybe there'll be some better ideas from other posters. That is a good solution. Another way is to make new functions that wrap the constructor. In sensor.py add: def fromId(id): return Sensor(id, None) def fromMonitor(monitor): return Sensor(None, monitor) Then client code is new_monitor = sensor.fromMonitor('XJ191') new_monitor = sensor.fromId('3433') Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about __init__ in a class
* shawn bright [EMAIL PROTECTED] [061113 19:46]: Hello there all. i have a class that i need to load some class variables depending on what is passed to the class, it would either be set up using one variable or another. The values for the class variables would be loaded from a database. But how it is looked up depends on how its called. Like this: class Sensor_Object(object): def __init__(self, id, monitor): if id: self.id = id load values from the database value1 = somevalue value2 = someOthervalue else: self.monitor = monitor get some values from database value1 = somevalue value2 = someothervalue now i could call it like this: new_monitor = sensor.Sensor('', 'XJ191') or new_monitor = sensor.Sensor('3433', '') to load based on the other variable. i think that this would work, but i was thinking that there must be a cleaner way to do it. Well, the code is basically ok, but I'd propose the following (it will help using the instances): class Sensor_Object(object): sensid = None monitor = None ... Basically, provide class variables shadowing your main instance attributes. I've also renamed id to sensid as id is an builtin function. (it's legal and ok to use id, but some tools like pylint like to complain about that style of shadowing.) The benefit is easy, in other methods, you can use code like this: if self.sensid is not None: instead of the more clumsy if hasattr(self, sensid): Andreas any suggestions ? sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about __init__ in a class
hey thanks, did not think about the possible consequences of the use of a built in as a variable name.-skOn 11/13/06, Andreas Kostyrka [EMAIL PROTECTED] wrote:* shawn bright [EMAIL PROTECTED] [061113 19:46]: Hello there all. i have a class that i need to load some class variables depending on what is passed to the class, it would either be set up using one variable or another. The values for the class variables would be loaded from a database. But how it is looked up depends on how its called. Like this: class Sensor_Object(object):def __init__(self, id, monitor): if id: self.id = id load values from the database value1 = somevalue value2 = someOthervalueelse: self.monitor = monitor get some values from database value1 = somevalue value2 = someothervalue now i could call it like this: new_monitor = sensor.Sensor('', 'XJ191') or new_monitor = sensor.Sensor('3433', '') to load based on the other variable. i think that this would work, but i was thinking that there must be a cleaner way to do it.Well, the code is basically ok, but I'd propose the following (it willhelp using the instances):class Sensor_Object(object):sensid = Nonemonitor = None ...Basically, provide class variables shadowing your main instanceattributes. I've also renamed id to sensid as id is an builtinfunction. (it's legal and ok to use id, but some tools like pylint like to complain about that style of shadowing.)The benefit is easy, in other methods, you can use code like this:if self.sensid is not None: instead of the more clumsyif hasattr(self, sensid): Andreas any suggestions ? sk ___ Tutor maillist-Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about __init__ in a class
* shawn bright [EMAIL PROTECTED] [061113 23:51]: hey thanks, did not think about the possible consequences of the use of a built in as a variable name. Well, the consequences are minimal: a) pylint complains by default about that. b) if you paste code into your function, you might get problems, as it might use the standard id. Please note, that self.id is safe from that, but you probably want to name the attribute of the instance the same as the constructor arguments. Andreas ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about classes and atributes
I think I don't understand the OOP in python, could anyone explain why this code works? class example: atribute = hello world print example.atribute Why you don't have to make an object of the class to access to the atribute? ( class example: atribute = hello world obj = example() print obj.atribute Thanks in advance. __ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y móviles desde 1 céntimo por minuto. http://es.voice.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about classes and atributes
Because your atribute is a class attribute: class C: ca = 123 print C.ca # 123 c1 = C() print c1.ca# 123 c1.ca = 140 print c1.ca# 140 print C.ca # 123 c2 = C() print c2.ca# 123 C.ca = 141 print C.ca # 141 print c1.ca# 140 print c2.ca# 141 Basically, when an instance does not have an attribute, it looks them up in the class, which might recurse into base classes. Furthermore, objects classes 101 material: class C: def method(self): print self c = C() print c.method # bound method to c print C.method # unbound method, checks that first argument is a C print C.__dict__[method] # function, does NOT check first argument. So basically, the whole self argument handling is magic that happpens during attribute lookup. Andreas Am Freitag, den 03.11.2006, 14:27 +0100 schrieb euoar: I think I don't understand the OOP in python, could anyone explain why this code works? class example: atribute = hello world print example.atribute Why you don't have to make an object of the class to access to the atribute? ( class example: atribute = hello world obj = example() print obj.atribute Thanks in advance. __ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y móviles desde 1 céntimo por minuto. http://es.voice.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor signature.asc Description: Dies ist ein digital signierter Nachrichtenteil ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about classes and atributes
Andreas Kostyrka escribió: Because your atribute is a class attribute: class C: ca = 123 print C.ca # 123 c1 = C() print c1.ca# 123 c1.ca = 140 print c1.ca# 140 print C.ca # 123 c2 = C() print c2.ca# 123 C.ca = 141 print C.ca # 141 print c1.ca# 140 print c2.ca# 141 Basically, when an instance does not have an attribute, it looks them up in the class, which might recurse into base classes. Furthermore, objects classes 101 material: class C: def method(self): print self c = C() print c.method # bound method to c print C.method # unbound method, checks that first argument is a C print C.__dict__[method] # function, does NOT check first argument. So basically, the whole self argument handling is magic that happpens during attribute lookup. Andreas Am Freitag, den 03.11.2006, 14:27 +0100 schrieb euoar: I think I don't understand the OOP in python, could anyone explain why this code works? class example: atribute = hello world print example.atribute Why you don't have to make an object of the class to access to the atribute? ( class example: atribute = hello world obj = example() print obj.atribute Thanks in advance. __ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y móviles desde 1 céntimo por minuto. http://es.voice.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Thank you for your answer and the examples. So without self it is an instance variable (like static in java/c#). But then, I don't understand how is it possible this in your example: c1.ca = 140 or down: print C.method Are you creating new atributes and methods at run time? Is that what has happened? In fact I have tried also this: class example: atribute = green obj = example() obj.a_new_atribute = white And even this seems to be correct: class example: atribute = green example._other_atribute = yellow So, in python, you can add methods at run time to an object, and even you can add them to a class at run time? __ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y móviles desde 1 céntimo por minuto. http://es.voice.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about classes and atributes
I think I don't understand the OOP in python, could anyone explain why this code works? class example: atribute = hello world print example.atribute Why you don't have to make an object of the class to access to the atribute? because that attribute is part of the Class object that's created when you declare a class. As you can see by the following code: class example: attribute = 'hello, world!' example class __main__.example at 0x00B528D0 there is actually a type of object called 'class.' when you make an instance of a class, a = example() a __main__.example instance at 0x00B40440 it is now a example object instance. Thank you for your answer and the examples. So without self it is an instance variable (like static in java/c#). But then, I don't understand how is it possible this in your example: c1.ca = 140 Because c1 is an instance of the class 'C', it has the attribute .ca already in it. This is a reference to the class attribute 'ca' which is equal to 123. However, when you change c1.ca, because the class attribute 'ca' is immutable (since it's an integer) a local copy of ca is created with the value 140 in it. C.ca is still 123. If you now do C.ca = 234, c1.ca is still 140, because it now has a local (instance) attribute called 'ca' that hides the class attribute. However, if you do something like this... class C: ca = 123 c1 = C() C.ca = 567 print c1.ca you will get an output of '567'. because c1 never got the local instance attribute to replace the reference to the class-wide attribute, so changing the C.ca will also affect c1.ca. or down: print C.method Are you creating new atributes and methods at run time? Is that what has happened? In fact I have tried also this: class example: atribute = green obj = example() obj.a_new_atribute = white And even this seems to be correct: class example: atribute = green example._other_atribute = yellow So, in python, you can add methods at run time to an object, and even you can add them to a class at run time? No, you're confusing Python with a compiled language. You're not adding methods to an object at run-time because there's not a distinction between runtime and compile-time in Python, because compile-time doesn't exist. You can add attributes to classes any time you want inside your program. Just like I can add an element to a list any time I want. a = [1,2,3] a.append(4) Classes are just objects, as lists are, and integers are, and everything else is as well. And when I execute the code, Python knows how to do all of these things. You see, an interpreted session is not the same as you think of 'at run time' being. For the most part, an interpreted session is exactly the same as if I were to type the code into a text document, save it, and execute it. So yeah, anywhere in your program you can add methods to classes, but really saying 'at run-time' is confusing terminology. It implies that if I were running someone else's program I could just add methods in on the fly whenever I wanted to. This is not true, unless they've enabled this functionality. HTH, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about classes and atributes
euoar [EMAIL PROTECTED] wrote in Thank you for your answer and the examples. So without self it is an instance variable (like static in java/c#). Without self it is a class attribute like static etc in C++/Java. An instance variable is one that is unique to an instance! Although I think it may be more powerful since I seem to recall that static members are not accessible via inheritance whereas Python class variables are. Also i'm not sure if statics can be reached via an instance whereas Python class variables can. But my Java/C# is very rusty on statics... Note also that you can go even further by specifying class methods too but they need special syntax. If you are only familiar with Java style statics you might find the concept of class variables and methods a little different in Python, which follows the traditional OOP style of Lisp and SmallTalk rather than the hybrid OOP style of Java etc. That is, a class variable/method is usually treated as one that applies to the class itself, or one that is shared by all instances. Java tend to use static methods as a replacement for traditional functions, ie. things you can do without creating an instance. You can do both things in any of the languages but conceptually they tend to be treated differently, especially since Python supports stand-alone functions. Are you creating new atributes and methods at run time? Is that what has happened? In fact I have tried also this: Yes, Python classes are a special type of container (really a special type of dictionary) , so just as you can add new keys to a dictionary you an add new attributes to a class or object at run time. So, in python, you can add methods at run time to an object, and even you can add them to a class at run time? I'm not sure about adding methods at run time, I've never tried it but I think the magic around the self parameter might not work. But you can definitely add attributes. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about classes and atributes
Alan Gauld wrote: euoar [EMAIL PROTECTED] wrote in So, in python, you can add methods at run time to an object, and even you can add them to a class at run time? I'm not sure about adding methods at run time, I've never tried it but I think the magic around the self parameter might not work. But you can definitely add attributes. Sure it works: In [1]: class foo(object): pass ...: In [2]: f=foo() In [3]: f.show() --- type 'exceptions.AttributeError'Traceback (most recent call last) D:\Projects\e3po\ipython console in module() type 'exceptions.AttributeError': 'foo' object has no attribute 'show' In [4]: def show(self): print Hi, I'm a foo ...: In [5]: foo.show=show In [6]: f.show() Hi, I'm a foo More advanced explanation: The magic around the self parameter is actually built-in to every function object (or its class, anyway). Functions have __get__() methods which means they can be used as descriptors. When Python evaluates f.show(), quite a few steps happen: - find the value of the show attribute in the class definition. This finds the show function object. - the function object has a __get__() method, so call show.__get__(obj) where obj is the original object being accessed. - the __get__() method wraps obj and the original function into a new callable object and returns that. - finally the temporary callable is actually called (by calling its __call__() method) and the wrapper adds the self parameter to the argument list and dispatches to the wrapped (original) function. The descriptor mechanism is only used for class attributes, not instance attributes, so if you want to add a method to an individual instance you have to do a little more work using new.instancemethod: In [12]: def show2(self): print I'm still a foo : The naive approach won't work: In [14]: f.show2 = show2 In [15]: f.show2() type 'exceptions.TypeError': show2() takes exactly 1 argument (0 given) In [17]: import new In [21]: f.show2 = new.instancemethod(show2, f) In [22]: f.show2() I'm still a foo I hope that makes sense to someone; I had to see it about 10 times myself before a light bulb went on. (This is number 10 :-) More info here and in the references: http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION00032 Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about classes and atributes
Thank you folks, for your excellent answers. This is really a fantastic place to learn python :-) __ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y móviles desde 1 céntimo por minuto. http://es.voice.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question
I don't get the output I would expect from the following. The variable clean1 gives me an empty string. But if i change the for loop to print i[26:40] I get all the info. what do I need to do to capture all the data to clean1? Thanks. a = open('arp.txt') file = a.read() file = file.split('\n') a.close() b = open('arplist.txt','w') clean1 = [] for i in file: ... clean1 = i[26:40] ... clean1 '' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about classes and atributes
Kent Johnson [EMAIL PROTECTED] wrote Alan Gauld wrote: I'm not sure about adding methods at run time, I've never Sure it works: In [1]: class foo(object): pass ...: In [4]: def show(self): print Hi, I'm a foo In [5]: foo.show=show In [6]: f.show() Hi, I'm a foo Cool! I'm constantly amazed at the power and simplicity of Python. More advanced explanation: Yes, it makes sense when its explained. But I'd never have intuitively thought of that! Thanks for the info Kent. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question
Doug Potter [EMAIL PROTECTED] wrote I don't get the output I would expect from the following. a = open('arp.txt') file = a.read() file = file.split('\n') Easier to do file = open('arp.txt').readlines() But file is a bad name since its an alias for open... b = open('arplist.txt','w') Not sure why you do this clean1 = [] clean is an empty list for i in file: ... clean1 = i[26:40] clean is now overwritten by a string until you reach the end of the file upon which clean1 will be an empty string clean1 '' Which it is... I think you may have meant to use the append method for i in file: clean1.append(i[26:40]) And since you can iterate over a file the whole thing shrinks to: clean1 = [] for i in open('arp.txt'): clean1.append(i[26:40]) print clean1 Or even more succinctly: clean1 = [i[26:40] for i in open('arp.txt')] print clean1 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question
Hi Doug, I'm not a Python guru, but shouldn't you be putting the output of file.split('\n') into a list, and not back into a string (for clarity's sake?). Also, if you have two trailing newlines on the file, your final string will be '', so you should be doing clean1.append(i[26:40]) in your for loop, right? Let me know if that helps... Jonathon Doug Potter wrote: I don't get the output I would expect from the following. The variable clean1 gives me an empty string. But if i change the for loop to print i[26:40] I get all the info. what do I need to do to capture all the data to clean1? Thanks. a = open('arp.txt') file = a.read() file = file.split('\n') a.close() b = open('arplist.txt','w') clean1 = [] for i in file: ... clean1 = i[26:40] ... clean1 '' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about pylab
Am 31.10.2006 um 08:35 schrieb shawn bright: hey there, i am trying to use a graph and chart app called matplotlib, but i cannot figgure out how to have it plot a simple chart over time. the docs say to use the function plot_date() but i cannot seem to get the values to agree. I am sending datetimes to the charting app for x, and the y is a list of values that the our equipment reports. sometimes there are lots of reports in a row, and i would like the chart to show it like that instead of plotting out every time as an evenly spaced tick on the x scale. Does this make any sense, what i am after here? Anyway, if any of you have much experience with this sort of thing, or may suggest a package (pylab is my first attempt) please send me some advice. thanks for your time, sk I am not sure if I get it right, could you give us some sample data and some code what you have tried? I never used plot_date, but I could give it a try. Regards, Markus ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about pylab
shawn bright wrote: hey there, i am trying to use a graph and chart app called matplotlib, but i cannot figgure out how to have it plot a simple chart over time. the docs say to use the function plot_date() but i cannot seem to get the values to agree. I am sending datetimes to the charting app for x, and the y is a list of values that the our equipment reports. sometimes there are lots of reports in a row, and i would like the chart to show it like that instead of plotting out every time as an evenly spaced tick on the x scale. Does this make any sense, what i am after here? Anyway, if any of you have much experience with this sort of thing, or may suggest a package (pylab is my first attempt) please send me some advice. I have used pylab to create a scatterplot of date vs value. The date values were created by calling pylab.date2num() on a datetime.datetime value. The axes were set up with this code: # Set up the xaxis ax = axes([0.05, 0.05, 0.9, 0.9]) ax.xaxis.set_major_locator(MinuteLocator(interval=10)) ax.xaxis.set_minor_locator(MinuteLocator()) ax.xaxis.set_major_formatter(DateFormatter(%H:%M)) I called pylab.scatter() to create the plot. HTH, Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about pylab
ok, looks like the date2num() function on a datetime.datetime object is working. So cool.i am very new at this, so i may be back ( read probably be back ). Thanks much for the tips.i appreciate it a lot.sk On 10/31/06, Kent Johnson [EMAIL PROTECTED] wrote: shawn bright wrote: hey there, i am trying to use a graph and chart app called matplotlib, but i cannot figgure out how to have it plot a simple chart over time. the docs say to use the function plot_date() but i cannot seem to get the values to agree. I am sending datetimes to the charting app for x, and the y is a list of values that the our equipment reports. sometimes there are lots of reports in a row, and i would like the chart to show it like that instead of plotting out every time as an evenly spaced tick on the x scale. Does this make any sense, what i am after here? Anyway, if any of you have much experience with this sort of thing, or may suggest a package (pylab is my first attempt) please send me some advice.I have used pylab to create a scatterplot of date vs value. The datevalues were created by calling pylab.date2num () on a datetime.datetimevalue. The axes were set up with this code:# Set up the xaxisax = axes([0.05, 0.05, 0.9, 0.9])ax.xaxis.set_major_locator(MinuteLocator(interval=10))ax.xaxis.set_minor_locator (MinuteLocator())ax.xaxis.set_major_formatter(DateFormatter(%H:%M))I called pylab.scatter() to create the plot.HTH,Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about pylab
hey there,i am trying to use a graph and chart app called matplotlib, but i cannot figgure out how to have it plot a simple chart over time.the docs say to use the function plot_date() but i cannot seem to get the values to agree. I am sending datetimes to the charting app for x, and the y is a list of values that the our equipment reports. sometimes there are lots of reports in a row, and i would like the chart to show it like that instead of plotting out every time as an evenly spaced tick on the x scale. Does this make any sense, what i am after here? Anyway, if any of you have much experience with this sort of thing, or may suggest a package (pylab is my first attempt) please send me some advice. thanks for your time,sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question abt numpy and Numeric...........
Folks, Is numpy different from Numeric; or are both one and the same ?? Kindly explain the difference .. Regards, Asrarahmed-- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question abt numpy and Numeric...........
Asrarahmed Kadri wrote: Folks, Is numpy different from Numeric; or are both one and the same ?? Kindly explain the difference .. See http://numpy.scipy.org/#older_array ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about number of threads
Hey there, i have an app that runs several processes as threads. using the threading.Thread() now, i have another app that does the same thing. Now, pretty soon, we will be combining all the features of the two packages together into one app. My question is, is there a limit on how many threads one GUI application can have running in the background ? Most of them are sleeping most of the time. They wake up and do something every 10 seconds, 20 minutes, etc... Any pitfalls out there i shoud know about ? thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about number of threads
shawn bright wrote: Hey there, i have an app that runs several processes as threads. using the threading.Thread() now, i have another app that does the same thing. Now, pretty soon, we will be combining all the features of the two packages together into one app. My question is, is there a limit on how many threads one GUI application can have running in the background ? Most of them are sleeping most of the time. They wake up and do something every 10 seconds, 20 minutes, etc... IIRC the number of threads is limited by memory - each thread requires some heap space for its stack, etc. I don't think you will have trouble until you have hundreds or thousands of threads. For example on my computer this program prints 1031 before it exits with thread.error: can't start new thread: import time from threading import Thread, activeCount def run(): while 1: time.sleep(1) while 1: print activeCount() t=Thread(target=run) t.setDaemon(1) t.start() (The setDaemon() call lets the application exit normally when it gets an exception; otherwise it hangs with all the threads running.) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about looping.
Doug Potter wrote: for i in routers: os.system('/bin/touch' %s) % i of course this dosn't work. Is there a simple way to get this done? Yep, someone already answered that you can create the file in write mode and then close it, but I wanted to add a little more in why your solution doesn't work. You're not interpolating the filename INTO the os.system string The following would work for i in routers: os.system('/bin/touch %s'%1) Granted, you should also provide a filename with a full path for simplicity. HTH Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about looping.
Hi, I at trying to create a bunch of text files in a single directory on a Linux system, something like this. import os routers = ['adnc-6321', 'adnp-2341', 'adnw-2632'] for i in routers: os.system('/bin/touch' %s) % i of course this dosn't work. Is there a simple way to get this done? Thanks for your time. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about looping.
Doug Potter wrote: Hi, I at trying to create a bunch of text files in a single directory on a Linux system, something like this. import os routers = ['adnc-6321', 'adnp-2341', 'adnw-2632'] for i in routers: os.system('/bin/touch' %s) % i of course this dosn't work. try using the following: for i in routers: os.system('/bin/touch %s' % i) Is there a simple way to get this done? You can also use the builtin file object: for i in routers: f = file(i, 'w') f.close() Thanks for your time. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Carlos Hanson Web Specialist Tigard-Tualatin School District 503.431.4053 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about sys.path and importing
This morning I was sternly warned by Wingware support not to leave my module of useful functions in Python25\Lib. So I put it in a subfolder in site-packages I named mine. Importing of or from that module, mycalc.py goes well, to my surprise, because of import sys [x for x in sys.path if site-packages in x] ['e:\\Python25\\lib\\site-packages', 'e:\\Python25\\lib\\site-packages\\win32', 'e:\\Python25\\lib\\site-packages\\win32\\lib', 'e:\\Python25\\lib\\site-packages\\Pythonwin', 'e:\\Python25\\lib\\site-packages\\wx-2.6-msw-unicode'] in which mine isn't included, even though other folders in site-packages are. Can someone explain this, please? Dick Moores ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about sys.path and importing
Dick Moores wrote: This morning I was sternly warned by Wingware support not to leave my module of useful functions in Python25\Lib. So I put it in a subfolder in site-packages I named mine. Importing of or from that module, mycalc.py goes well, to my surprise, because of import sys [x for x in sys.path if site-packages in x] ['e:\\Python25\\lib\\site-packages', 'e:\\Python25\\lib\\site-packages\\win32', 'e:\\Python25\\lib\\site-packages\\win32\\lib', 'e:\\Python25\\lib\\site-packages\\Pythonwin', 'e:\\Python25\\lib\\site-packages\\wx-2.6-msw-unicode'] in which mine isn't included, even though other folders in site-packages are. Can someone explain this, please? If the program that does the import is also in site-packages\mine, that would explain it. When you run a script its directory is added to sys.path. Normally you will need to either - make 'mine' be a package, by creating an empty file named site-packages\mine\__init__.py, and changing your imports to include the package name (from mine import mycalc), or - add site-packages\mine to sys.path, maybe by creating a .pth file. http://www.python.org/doc/2.4.3/lib/module-site.html Gee, maybe I should just invite you over and we can talk ;) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about sys.path and importing
At 11:38 AM 10/3/2006, Kent Johnson wrote: Normally you will need to either - make 'mine' be a package, by creating an empty file named site-packages\mine\__init__.py, and changing your imports to include the package name (from mine import mycalc), or - add site-packages\mine to sys.path, maybe by creating a .pth file. http://www.python.org/doc/2.4.3/lib/module-site.html I went with your first way, and it works with a script in python25\dev: # 1test-8.py from mine import mycalc print mycalc.numberCommas(12341234123) Evaluating 1test-8.py 12,341,234,123 But fails here: # 1test-9.py from mine import mycalc from mycalc import numberCommas print numberCommas(12341234123) Evaluating 1test-9.py Traceback (most recent call last): File string, line 1, in string ImportError: No module named mycalc I guess I can live with that. Gee, maybe I should just invite you over and we can talk ;) Careful now. I just might show up! Dick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about sys.path and importing
Dick Moores wrote: At 11:38 AM 10/3/2006, Kent Johnson wrote: Normally you will need to either - make 'mine' be a package, by creating an empty file named site-packages\mine\__init__.py, and changing your imports to include the package name (from mine import mycalc), or - add site-packages\mine to sys.path, maybe by creating a .pth file. http://www.python.org/doc/2.4.3/lib/module-site.html I went with your first way, and it works with a script in python25\dev: # 1test-8.py from mine import mycalc print mycalc.numberCommas(12341234123) Evaluating 1test-8.py 12,341,234,123 But fails here: # 1test-9.py from mine import mycalc from mycalc import numberCommas print numberCommas(12341234123) Evaluating 1test-9.py Traceback (most recent call last): File string, line 1, in string ImportError: No module named mycalc Well this is different code. Try what you did in the first one: from mine import mycalc print mycalc.numberCommas(12341234123) or from mine.mycalc import numberCommas Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about sys.path and importing
At 12:30 PM 10/3/2006, you wrote: Dick Moores wrote: At 11:38 AM 10/3/2006, Kent Johnson wrote: Normally you will need to either - make 'mine' be a package, by creating an empty file named site-packages\mine\__init__.py, and changing your imports to include the package name (from mine import mycalc), or - add site-packages\mine to sys.path, maybe by creating a .pth file. http://www.python.org/doc/2.4.3/lib/module-site.html I went with your first way, and it works with a script in python25\dev: # 1test-8.py from mine import mycalc print mycalc.numberCommas(12341234123) Evaluating 1test-8.py 12,341,234,123 But fails here: # 1test-9.py from mine import mycalc from mycalc import numberCommas print numberCommas(12341234123) Evaluating 1test-9.py Traceback (most recent call last): File string, line 1, in string ImportError: No module named mycalc Well this is different code. Yes, that was my point. Sorry I didn't make that clear. Try what you did in the first one: from mine import mycalc print mycalc.numberCommas(12341234123) or from mine.mycalc import numberCommas Good! Didn't know I could do from mine.mycalc import numberCommas. Thanks, Dick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about startswith() and endswith() in 2.5
http://www.python.org/doc/lib/string-methods.html has = startswith( prefix[, start[, end]]) Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of suffixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position. Changed in version 2.5: Accept tuples as prefix. == and endswith( suffix[, start[, end]]) Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. Changed in version 2.5: Accept tuples as suffix. == Through experimentation I now see a use for a tuple in which start and end are indexes (as with the startswith() and endswith() of 2.4.3): s = qwerty s.startswith(er,2,3) False s.startswith(er,2,4) True but s.startswith(er,q,ty) Traceback (most recent call last): File pyshell#55, line 1, in module s.startswith(er,q,ty) TypeError: slice indices must be integers or None or have an __index__ method On http://docs.python.org/whatsnew/other-lang.html I found == The startswith() and endswith() methods of string types now accept tuples of strings to check for. def is_image_file (filename): return filename.endswith(('.gif', '.jpg', '.tiff')) This is the only example I've been able to find in the documentation that uses the new tuple of strings, and I don't understand it. The function is_image_file() will return filenames ending in '.gif', but what do '.jpg' (as start) and '.tiff' (as end) do? What kind of data(?) would this function be applied to? A Python list of filenames? Thanks, Dick Moores ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about startswith() and endswith() in 2.5
Dick Moores wrote: s.startswith(er,q,ty) Traceback (most recent call last): File pyshell#55, line 1, in module s.startswith(er,q,ty) TypeError: slice indices must be integers or None or have an __index__ method On http://docs.python.org/whatsnew/other-lang.html I found == The startswith() and endswith() methods of string types now accept tuples of strings to check for. def is_image_file (filename): return filename.endswith(('.gif', '.jpg', '.tiff')) This is the only example I've been able to find in the documentation that uses the new tuple of strings, and I don't understand it. The function is_image_file() will return filenames ending in '.gif', but what do '.jpg' (as start) and '.tiff' (as end) do? What kind of data(?) would this function be applied to? A Python list of filenames? You're missing something. Do you see the doubled parentheses in the call to endswith()? filename.endswith(('.gif', '.jpg', '.tiff')) is a call to endswith() with a *single* argument, the tuple ('.gif', '.jpg', '.tiff'). The start and end arguments are omitted. On the other hand, your call s.startswith(er,q,ty) is a call to startswith() with three arguments, the strings 'er', 'q' and 'ty'. To write is_image_file() prior to 2.5 you would have to write something like this: def is_image_file(filename): for extn in ('.gif', '.jpg', '.tiff'): if filename.endswith(extn): return True return False Allowing the first argument to endswith() to be a tuple simplifies this common usage. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about startswith() and endswith() in 2.5
Dick Moores rdm at rcblue.com writes: snip endswith( suffix[, start[, end]]) Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. snip s.startswith(er,q,ty) Traceback (most recent call last): File pyshell#55, line 1, in module s.startswith(er,q,ty) TypeError: slice indices must be integers or None or have an __index__ method snip def is_image_file (filename): return filename.endswith(('.gif', '.jpg', '.tiff')) snip function is_image_file() will return filenames ending in '.gif', but what do '.jpg' (as start) and '.tiff' (as end) do? What kind of data(?) would this function be applied to? A Python list of filenames? Note that endswith(('.gif', '.jpg', '.tiff')) is a function call with ONE parameter: the tuple ('.gif', '.jpg', '.tiff') - hence the double parentheses. This parameter is the suffix. The optional start and end parameters are not specified. You could read it like if the filename ends with .gif or .jpg or .tiff. In older Python versions, you could implement the same functionality as: if s.endswith('.gif') or s.endswith('.jpg') or s.endswith('.tiff') This is in contrast with the example you give above, where startswith(er,q,ty) is a function call with three separate parameters, all of them strings. Since start (q) and end (ty) must be integers, this call crashes. Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about startswith() and endswith() in 2.5
Thanks, Kent and Andrei! I sure did miss those doubled parentheses. s = qwerty s.startswith((er,z,ty,qw,98768976,uytruytr)) True s.startswith((er,z,ty,qe,98768976,uytruytr)) False s.startswith((er,z,rty,qe,98768976,uytruytr), 2) True s.startswith((er,z,rty,qe,98768976,uytruytr), 4) False Dick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about startswith() and endswith() in 2.5
-Original Message- Date: Mon, 25 Sep 2006 02:59:45 -0700 From: Dick Moores [EMAIL PROTECTED] Subject: [Tutor] Question about startswith() and endswith() in 2.5 To: tutor@python.org Message-ID: [EMAIL PROTECTED] Content-Type: text/plain; charset=us-ascii; format=flowed http://www.python.org/doc/lib/string-methods.html has = startswith( prefix[, start[, end]]) Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of suffixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position. Changed in version 2.5: Accept tuples as prefix. == and endswith( suffix[, start[, end]]) Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. Changed in version 2.5: Accept tuples as suffix. == Through experimentation I now see a use for a tuple in which start and end are indexes (as with the startswith() and endswith() of 2.4.3): s = qwerty s.startswith(er,2,3) False s.startswith(er,2,4) True but s.startswith(er,q,ty) Traceback (most recent call last): File pyshell#55, line 1, in module s.startswith(er,q,ty) TypeError: slice indices must be integers or None or have an __index__ method On http://docs.python.org/whatsnew/other-lang.html I found == The startswith() and endswith() methods of string types now accept tuples of strings to check for. def is_image_file (filename): return filename.endswith(('.gif', '.jpg', '.tiff')) This is the only example I've been able to find in the documentation that uses the new tuple of strings, and I don't understand it. The function is_image_file() will return filenames ending in '.gif', but what do '.jpg' (as start) and '.tiff' (as end) do? What kind of data(?) would this function be applied to? A Python list of filenames? Thanks, Dick Moores Hello, Dick. Let's compare your final startswith method and the endswith method in is_image_file: s.startswith(er,q,ty) filename.endswith(('.gif', '.jpg', '.tiff')) Notice that, while startswith has THREE parameters, endswith has only ONE. ('.gif', '.jpg', '.tiff') is a tuple, and the interpreter sees it as a single parameter. In other words your method is passing the following parameters: prefix = er start = q end = ty while the example method is passing: suffix = ('.gif', '.jpg', '.tiff') start = None end = None Does that make sense? Good luck. Regards, Barry [EMAIL PROTECTED] 541-302-1107 We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about startswith() and endswith() in 2.5
At 09:04 AM 9/25/2006, Carroll, Barry wrote: Hello, Dick. Let's compare your final startswith method and the endswith method in is_image_file: s.startswith(er,q,ty) filename.endswith(('.gif', '.jpg', '.tiff')) Notice that, while startswith has THREE parameters, endswith has only ONE. ('.gif', '.jpg', '.tiff') is a tuple, and the interpreter sees it as a single parameter. In other words your method is passing the following parameters: prefix = er start = q end = ty while the example method is passing: suffix = ('.gif', '.jpg', '.tiff') start = None end = None Does that make sense? Sure does now. Thanks, Barry Dick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about headers and smtplib
OK, this worked, please disregard my last. The online docs at python.org told me the answer to that one. Between their example and yours, i am able to make it work. thanks a whole bunch ! shawnOn 7/31/06, Justin Ezequiel [EMAIL PROTECTED] wrote: When I first started with Python, I used MimeWriter to create E-mails.Then some mail servers rejected my E-mails.Some research (google) indicated (to me) that I needed a MIME-Version header.(Can't recall now if I also needed a Content-Type header.) Anyway, more research (Python docs) indicated that I should use theemail package instead.I have been doing so since and have not had reports of anymore rejected E-mails.Hope this helps. import email from email.MIMENonMultipart import MIMENonMultipart from email.Utils import formataddr format_addresses = lambda pairs: ', '.join([formataddr(pair) forpair in pairs]) msg = MIMENonMultipart('text', 'plain', charset='us-ascii') msg.set_payload('Foo Bar') msg.add_header('From', formataddr(('Justin', '[EMAIL PROTECTED]'))) msg.add_header('To', format_addresses([('Justin', '[EMAIL PROTECTED]'),('You', '[EMAIL PROTECTED]')])) print msg.as_string()Content-Type: text/plain; charset=us-ascii MIME-Version: 1.0From: Justin [EMAIL PROTECTED]To: Justin [EMAIL PROTECTED], You [EMAIL PROTECTED]Foo Bar ___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about headers and smtplib
Hey there, me again with another question about headers.. if i use my python script to send an email, it gets rejected by some providers. but another app that i use can send the same email and it gets thru. i have sent myself test messages from both apps and looked at the headers. the only difference in one from the other is that in the headers of the other app (not my python script) there exist the following lines: MIME-Version: 1.0 X-Mailer: OstroSoft SMTP Control (4.0.20) Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7-bit i do not understand how to make mine work and include (or configure to) the above example. anyone point me in a right direction ? thanks, shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about headers and smtplib
shawn bright wrote: the only difference in one from the other is that in the headers of the other app (not my python script) there exist the following lines: MIME-Version: 1.0 X-Mailer: OstroSoft SMTP Control (4.0.20) Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7-bit i do not understand how to make mine work and include (or configure to) the above example. anyone point me in a right direction ? It's hard to tell what the problem is without seeing the error messages -- do you get a bounce? Is there anything in your logfile? Have you tried set_debuglevel and looking at the output? If you have information there, but don't know how to interpret it, post it here and we'll take a look. You could try adding the Content-Type header to your own messages. People configure mailservers in a lot of weird ways, and it's possible that some mailservers reject emails without a Content-Type header.. Dustin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about headers and smtplib
When I first started with Python, I used MimeWriter to create E-mails. Then some mail servers rejected my E-mails. Some research (google) indicated (to me) that I needed a MIME-Version header. (Can't recall now if I also needed a Content-Type header.) Anyway, more research (Python docs) indicated that I should use the email package instead. I have been doing so since and have not had reports of anymore rejected E-mails. Hope this helps. import email from email.MIMENonMultipart import MIMENonMultipart from email.Utils import formataddr format_addresses = lambda pairs: ', '.join([formataddr(pair) for pair in pairs]) msg = MIMENonMultipart('text', 'plain', charset='us-ascii') msg.set_payload('Foo Bar') msg.add_header('From', formataddr(('Justin', '[EMAIL PROTECTED]'))) msg.add_header('To', format_addresses([('Justin', '[EMAIL PROTECTED]'), ('You', '[EMAIL PROTECTED]')])) print msg.as_string() Content-Type: text/plain; charset=us-ascii MIME-Version: 1.0 From: Justin [EMAIL PROTECTED] To: Justin [EMAIL PROTECTED], You [EMAIL PROTECTED] Foo Bar ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about type str
Hey there,i have an app with this line.sys.stderr.write(GET DATA %s %d %d\n (sound, time_limit, digit_count))it is failing with the following error.Traceback (most recent call last): File /usr/share/asterisk/agi-bin/ast_agi_test.agi, line 88, in ? entered_digits = getNumber(welcome, time_limit, password_digits) File /usr/share/asterisk/agi-bin/ast_agi_test.agi, line 72, in getNumber sys.stderr.write(GET DATA %s %d %d\n (sound, time_limit, digit_count))TypeError: 'str' object is not callableanyone know what i may be doing wrong here?thanksshawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about type str
On Sat, 2006-07-29 at 09:26 -0500, shawn bright wrote: Hey there, i have an app with this line. sys.stderr.write(GET DATA %s %d %d\n (sound, time_limit, digit_count)) sys.stderr.write(GET DATA %s %d %d\n % (sound, time_limit, digit_count)) ^ You meant to do string interpolation, but left out the interpolation (formating) operator. So the parenthesized expression looked like a function call. it is failing with the following error. Traceback (most recent call last): File /usr/share/asterisk/agi-bin/ast_agi_test.agi, line 88, in ? entered_digits = getNumber(welcome, time_limit, password_digits) File /usr/share/asterisk/agi-bin/ast_agi_test.agi, line 72, in getNumber sys.stderr.write(GET DATA %s %d %d\n (sound, time_limit, digit_count)) TypeError: 'str' object is not callable anyone know what i may be doing wrong here? thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about type str
gee whiz, i thought i had poured over that line sufficiently.It works now. imagine that.thanks,shawnOn 7/29/06, Python [EMAIL PROTECTED] wrote:On Sat, 2006-07-29 at 09:26 -0500, shawn bright wrote: Hey there, i have an app with this line. sys.stderr.write(GET DATA %s %d %d\n (sound, time_limit, digit_count))sys.stderr.write(GET DATA %s %d %d\n % (sound, time_limit, digit_count)) ^You meant to do string interpolation, but left out the interpolation(formating) operator.So the parenthesized _expression_ looked like afunction call. it is failing with the following error. Traceback (most recent call last): File /usr/share/asterisk/agi-bin/ast_agi_test.agi, line 88, in ? entered_digits = getNumber(welcome, time_limit, password_digits) File /usr/share/asterisk/agi-bin/ast_agi_test.agi, line 72, in getNumber sys.stderr.write(GET DATA %s %d %d\n (sound, time_limit, digit_count)) TypeError: 'str' object is not callable anyone know what i may be doing wrong here? thanks shawn ___ Tutor maillist- Tutor@python.org http://mail.python.org/mailman/listinfo/tutor--Lloyd KvamVenix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about metaclasses
hi pyguruscan you please tell me why we need metaclasses and how to use themthanks a lotAnil Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail Beta.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about metaclasses
anil maran wrote: hi pygurus can you please tell me why we need metaclasses and how to use them Hmm...metaclasses are an advanced topic, first exposure to them usually causes one's brain to explode. Fortunately the condition is only temporary :-) Basically a metaclass is the type of a class, or the type of a type. Think about it this way - every object has a type. The type of 1 is int, the type of 'a' is str. In [16]: type(1) Out[16]: type 'int' In [17]: type('a') Out[17]: type 'str' Note that type 'int' is just the printed representation of the type int: In [19]: type(1) == int Out[19]: True In [20]: print int type 'int' But int and str are themselves objects - what is their type? In [18]: type(int) Out[18]: type 'type' In [21]: type(str) Out[21]: type 'type' Why might you care? In general, it is the type of an object that determines its behaviour. The behaviour of an int is determined by the int type. What determines the behaviour of a class? Its type! So if you want to customize the behaviour of a class, you create a custom metatype for the class. That is a very brief introduction. Here are some relatively introductory articles. You can find more examples by searching the Python Cookbook and comp.lang.python for metaclass. Don't expect to understand this the first time. http://www-128.ibm.com/developerworks/linux/library/l-pymeta.html http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/ Here is Guido's brief explanation: http://www.python.org/download/releases/2.2.3/descrintro/#metaclasses Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question regarding commit/backout of a message using the pymqi module
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hi everyone, Could someone help explain what I am doing wrong in this code block? This code block is an excerpt from a larger file that receives transmitted files via IBM WebSphere MQSeries an drops it to the local file system. Transmission of the file works as designed but it has a flaw. If the file cannot be created for whatever reason, the transmitted message is lost. What I am trying to do is ensure that a file transmit is considered successful only after the created file's checksum matches. If not, the code should treat it as an error and roll back the message to MQSeries without a commit. The basis for this should be around the pymqi.QueueManager class which is named mq in the block listed below. On execution, I get the traceback of: Traceback (most recent call last): File M:\MQ\MQ\Scripts\receiver.py, line 269, in ? receiver.run() File M:\MQ\MQ\Scripts\receiver.py, line 109, in run self.connect() File M:\MQ\MQ\Scripts\receiver.py, line 118, in connect self.qm.begin() File c:\python24\lib\site-packages\pymqi.py, line 738, in begin raise MQMIError(rv[0], rv[1]) pymqi.MQMIError: MQI Error. Comp: 1, Reason 2121: WARNING: MQRC_NO_EXTERNAL_PARTICIPANTS Do you have any idea why this might be occurring? class Receiver(object): def __init__(self,qm_name,queue_name): self.qm_name = qm_name self.queue_name = queue_name # Will be set later self.qm = None self.message = None def run(self): self.connect() self.get() def connect(self): Connect to queue manager try: self.qm = mq.QueueManager(options.qmanager.upper() ) self.qm.begin() except mq.PYIFError, err: mqevlog.event(error,err) sys.exit(1) def get(self): Get a message from queue. queue = mq.Queue(self.qm, self.queue_name) pmo = mq.pmo(Options = CMQC.MQPMO_SYNCPOINT) md = mq.md() while True: try: var = queue.get(self.message, md, pmo ) except mq.MQMIError,e: if e.reason != CMQC.MQRC_NO_MSG_AVAILABLE: mqevlog.event(error,e) sys.exit(1) break else: buff = StringIO(var) tree = ElementTree(file=buff) # Extract required elements and assign to local variables key = this should be a well-kept secret file_name = tree.find(dest).text creation_time = tree.find(creation_time).text contents = tree.find(contents).text check = tree.find(checksum).text #Decode temp file original = file_encoder.decode(contents) # Drop file to disk if os.path.exists(file_name) is False: open(file_name,wb).write(original) else: mqevlog.event(sys.argv[0],error,Output file path/name already exists) sys.exit(1) # Get checksum of newly created file sum=csums.getsum(file_name) # Compare checksum of created file with value transmitted if csums.checksum_compare(sys.argv[0],sum,check,file_name) == True: queue.commit() sys.exit(0) else: queue.backout() mqevlog.event(error,CheckSums of received/transmitted files do not match) sys.exit(1) Any help/insight you can provide on this would be greatly appreciated. - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: [EMAIL PROTECTED] Linux User Number: #201204 -BEGIN PGP SIGNATURE- Version: GnuPG v1.2.1 (MingW32) Comment: GnuPT 2.7.2 iD8DBQFEmoCtDvn/4H0LjDwRAonCAKCAiWPpO1UcXWMKIP8xPzCtzP6eLACeMWFO qmHgdq/nI3gJ1v3jquDKnu8= =Ga33 -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question on Logging Module
Hi, I have written a number of scripts which write to a remote log. I am using the logging module to produce detailed output. Two questions on this module: 1. One of the scripts loops around for a specified period of time. Previously it would print a message to the console detailing how long it had been waiting for. I used the \r to ensure each message just printed over the previous message, so I didnt get a hundreds of similiar lines with just a short time increase specified. I am not sure how to do this now that I am using the logging module. I just want to print this line to the remote file but just write over the previous log message. Any ideas ? Thanks Kieran-- Behind every great man, there is a great woman. Behind that woman is Mr.T. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about network server in python
Hi there, I am wondering if somebody to could answer a question about sockets. I have a socket that is listening, and a client program connects to it. The client program transfers a name over, and then disconnects from the socket. Now, how that is done is using a socket.close() call to shut down the entire socket. My question is: Is there a way to have the socket close the connection, yet stay open for the next client that comes along and connects to the server? I have my already written code below for further documentation. Thanks! while 1: s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((self.ipAddr,self.port)) s.listen(5) print The port is: , self.port client,addr=s.accept() while 1: try: if addr[0] == self.remoteIpAddr: client.send(Connected to the server\n) msg=client.recv(1024) msg=msg.strip() if msg in 'exit': s.close() #Is there a different way to write this? time.sleep(30) print exiting break if len(msg) 0: ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about network server in python
I think the problem here is the 'break' statement. Does it not put you outside the while loop whereas in order to keep the server socket open you need it to loop forever. I also think that the s.accept should be inside the while loop. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about network server in python
import socket host = '' port = 57000 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((host,port)) s.listen(5) while 1: client,addr=s.accept() client.send(Connected to the server\n) #if someCondition: # cliente.close() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about network server in python
Peter Jessop wrote: I think the problem here is the 'break' statement. Does it not put you outside the while loop whereas in order to keep the server socket open you need it to loop forever. I also think that the s.accept should be inside the while loop. There are two loops, I think you missed the outer loop. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about network server in python
Tino Dai wrote: Hi there, I am wondering if somebody to could answer a question about sockets. I have a socket that is listening, and a client program connects to it. The client program transfers a name over, and then disconnects from the socket. Now, how that is done is using a socket.close() call to shut down the entire socket. My question is: Is there a way to have the socket close the connection, yet stay open for the next client that comes along and connects to the server? I have my already written code below for further documentation. Thanks! while 1: s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((self.ipAddr,self.port)) s.listen(5) print The port is: , self.port client,addr=s.accept() while 1: try: if addr[0] == self.remoteIpAddr: client.send(Connected to the server\n) msg=client.recv(1024) msg=msg.strip() if msg in 'exit': s.close() #Is there a different way to write this? I think you want to close the client socket - client.close() - rather than the master socket. You might be interested in the SocketServer library which helps to write simple socket servers such as this. One advantage of using SocketServer is it makes it trivial to convert your server to a threaded or forked server. Here are some examples: http://www.amk.ca/python/simple/fingerd.py.html http://examples.oreilly.com/pythonian/ see example 19-5 Kent time.sleep(30) print exiting break if len(msg) 0: ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hi Everyone I did a comparison of the output between the perl and python methodology. They do basically the same thing but the perl form seems to be more true The python method inserts extra blank lines after each hex value line. For example: Original text: def handler(signal, frame): Trap signal interrupts if they occur Converted In Perl: def handler%28signal%2C frame%29%3A %22%22%22 Trap signal interrupts if they occur %22%22%22 Converted In Python: def handler%28signal%2C frame%29%3A %22%22%22 Trap signal interrupts if they occur %22%22%22 Does anyone know why this might be? Is the print statement inserting a artificial new line character? If so, how cam I remove that? The python code I am using is: import re,sys for line i open(r'e:\pycode\sigh.txt','rb'): print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) The file is being opened in rb mode because eventually binary files would be opened via this method as well. Alan Gauld wrote: a = open(r'e:\pycode\csums.txt','rb').readlines() for line in a: print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) Or just for line in open(r'e:\pycode\csums.txt','rb'): print. Breaking down the command, you appear to be calling an un-named function to act against any characters trapped by the regular expression. Not familiar with lamda :). You ae absolutely right. It creates an un-named(or anonymous function). :-) The un-named function does in-place transformation of the character to the established hex value. Its actually the call to re.sub() that makes in in place. How would you reverse the process from a python point of view? Just write a reverse function for the lamda... Alan G. - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: [EMAIL PROTECTED] Linux User Number: #201204 -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdZ9oDvn/4H0LjDwRAo89AJwJ64+wpfOnboxw4/+w8PhmZBzgwACfYH7C VPW5VPyqSWhAUgkoOBorjJM= =bOj0 -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor