Re: [Tutor] Static Variable in Functions
Steven D'Aprano wrote: Most of the common built-in Python objects are immutable: ... while a few are mutable: lists dicts sets Also, bytearrays. -- Tom Zych / freethin...@pobox.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use a str object, to find the class in exact name?
Thanks for excellent explanations. I almost got this working. I just have one more problem, that is: When user enter incorrect number of arguments for a method, I naturally get a type error. I could probably fix that with try and catch, but that is not very explanatory to the user. Is there a way to get expected number of arguments to the method so that I can generate an error report? You can find my codes as attachment. I have split them into two files. In order to run it, you should run cli.py like: python cli.py Thanks in advance, Yaşar Arabacı 15-03-2011 05:39, bob gailer yazmış: On 3/14/2011 8:49 PM, Yaşar Arabacı wrote: As I try to implement things with getattr, I am getting a really strange error. This is my file: Various interspersed comments: #!/usr/bin/env python # -*- encoding:utf-8 -*- class global_variables: It is customary to start class names with an uppercase letter Holds class attributes, so that other classes can share them products = 0 best_bundle = [] class dispatcher: def GetMethod(self,class_name,method_name): It is customary to start method names with a lowercase letter This method first finds a class if desired classexists. Then, instansites it, and returns a reference to desired method of the instance it created. from sys import modules It is customary to place import statements close to the top of the program, not in any class or function. module = modules[self.__module__] if hasattr(module,class_name): What are the module's attributes? insert print dir(module) to see ALL the attributes. print #debug : hasattr is true cls = getattr(module,class_name) else: print #debug : hasattr is false return None if we get a valid class, lets instantie it if cls: a=cls() else: return None return hasattr(a,method_name) and getattr(a,method_name) or None def dispatch_command(self): Gets command from user, finds appropriate Class/method to run and then runs it. Beware of the fact that, to be able to successfully run the method, method should take exactly two arguments, arg 1: instance of class which method resides (e.g. self) arg 2: list of other needed variables list of other variables can be used to get as many variables as possible command = raw_input() args = command.split( ) if len(args) 2: return None method = self.GetMethod(args[0],args[1]) return method and method(args[2:]) or None class calculate(global_variables): def bundle(self,args): print your best bundle is -- a = dispatcher() a.dispatch_command() Alternative 1 - put all the user-callable class definitions inside a Container class (or whatever name you want) - then use getattr on the Container class class Container: class Calculate(global_variables): def bundle(self,args): print your best bundle is -- Alternative 2 - use the following to create a dictionary of classes in which you look up the desired class by name import sys, inspect thisModule = sys.modules[__name__] classDict = dict((name.lower(), value) for name, value in inspect.getmembers(thisModule, inspect.isclass)) ... cls = classDict[className] Alternative 3 cls = getattr(module,class_name) try: if issubclass(cls, global_variables) a=cls() except TypeError: pass I wanted to see what happens when someone gives an nonexistent function. But when I put a b, it gives me error, when I put c d it doesn't. I don't have either a or c classes, but a somehow causes problems :S This is what I did: yasar@yasar-laptop:~/best_buy ./main.py a b #debug : hasattr is true Traceback (most recent call last): File ./main.py, line 57, in module a.dispatch_command() File ./main.py, line 44, in dispatch_command method = self.GetMethod(args[0],args[1]) File ./main.py, line 25, in GetMethod a=cls() AttributeError: dispatcher instance has no __call__ method The error tells you what a is. Isn't it obvious now? Remember to read and understand such messages. yasar@yasar-laptop:~/best_buy ./main.py c d #debug : hasattr is false This is supposed to an generic command line tool, to be used with any kind of module, you should import whatever module you want to use as book like; import xxx as book License Notice: This program comes with absolutely no warranty, use at your own risk, you can use, modify, redistribute, or do whatever else you want to do with it provided that: **Author of this code cannot be held responsible for any damage this code may do. Author: Yasar Arabaci import main as book class Dispatcher: force_subclass = Best_buy # Enter name of base class, or None to enable all! def getMethod(self,class_name,method_name): This method first finds a class if desired class exists. First letter, of the class name must be uppercased! Then, instansites it, and returns a reference to desired method of the instance it created. if hasattr(book,class_name): if self.force_subclass: # if this option is enabled, we will only get subclasses try: if not
Re: [Tutor] How to use a str object, to find the class in exact name?
I hate to jump on this one a little late, but even getattr() is kind of ghetto (though exec/eval is worse ;). For setting up shell scripts or CLIs, the usual route is the optparse module. - Japhy 2011/3/15 Yaşar Arabacı yasar11...@gmail.com: Thanks for excellent explanations. I almost got this working. I just have one more problem, that is: When user enter incorrect number of arguments for a method, I naturally get a type error. I could probably fix that with try and catch, but that is not very explanatory to the user. Is there a way to get expected number of arguments to the method so that I can generate an error report? You can find my codes as attachment. I have split them into two files. In order to run it, you should run cli.py like: python cli.py Thanks in advance, Yaşar Arabacı 15-03-2011 05:39, bob gailer yazmış: On 3/14/2011 8:49 PM, Yaşar Arabacı wrote: As I try to implement things with getattr, I am getting a really strange error. This is my file: Various interspersed comments: #!/usr/bin/env python # -*- encoding:utf-8 -*- class global_variables: It is customary to start class names with an uppercase letter Holds class attributes, so that other classes can share them products = 0 best_bundle = [] class dispatcher: def GetMethod(self,class_name,method_name): It is customary to start method names with a lowercase letter This method first finds a class if desired classexists. Then, instansites it, and returns a reference to desired method of the instance it created. from sys import modules It is customary to place import statements close to the top of the program, not in any class or function. module = modules[self.__module__] if hasattr(module,class_name): What are the module's attributes? insert print dir(module) to see ALL the attributes. print #debug : hasattr is true cls = getattr(module,class_name) else: print #debug : hasattr is false return None if we get a valid class, lets instantie it if cls: a=cls() else: return None return hasattr(a,method_name) and getattr(a,method_name) or None def dispatch_command(self): Gets command from user, finds appropriate Class/method to run and then runs it. Beware of the fact that, to be able to successfully run the method, method should take exactly two arguments, arg 1: instance of class which method resides (e.g. self) arg 2: list of other needed variables list of other variables can be used to get as many variables as possible command = raw_input() args = command.split( ) if len(args) 2: return None method = self.GetMethod(args[0],args[1]) return method and method(args[2:]) or None class calculate(global_variables): def bundle(self,args): print your best bundle is -- a = dispatcher() a.dispatch_command() Alternative 1 - put all the user-callable class definitions inside a Container class (or whatever name you want) - then use getattr on the Container class class Container: class Calculate(global_variables): def bundle(self,args): print your best bundle is -- Alternative 2 - use the following to create a dictionary of classes in which you look up the desired class by name import sys, inspect thisModule = sys.modules[__name__] classDict = dict((name.lower(), value) for name, value in inspect.getmembers(thisModule, inspect.isclass)) ... cls = classDict[className] Alternative 3 cls = getattr(module,class_name) try: if issubclass(cls, global_variables) a=cls() except TypeError: pass I wanted to see what happens when someone gives an nonexistent function. But when I put a b, it gives me error, when I put c d it doesn't. I don't have either a or c classes, but a somehow causes problems :S This is what I did: yasar@yasar-laptop:~/best_buy ./main.py a b #debug : hasattr is true Traceback (most recent call last): File ./main.py, line 57, in module a.dispatch_command() File ./main.py, line 44, in dispatch_command method = self.GetMethod(args[0],args[1]) File ./main.py, line 25, in GetMethod a=cls() AttributeError: dispatcher instance has no __call__ method The error tells you what a is. Isn't it obvious now? Remember to read and understand such messages. yasar@yasar-laptop:~/best_buy ./main.py c d #debug : hasattr is false ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Processing Financial Calculations using Python
Are there specific Python commands to process present value, future value and net present value? Thanks. Sincerely, Carla Jenkins ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Processing Financial Calculations using Python
On Tue, Mar 15, 2011 at 7:00 PM, Carla Jenkins carlarjenk...@yahoo.comwrote: Are there specific Python commands to process present value, future value and net present value? Thanks. http://tinyurl.com/4j5exao http://tinyurl.com/67x2to8 HTH, Wayne Sincerely, Carla Jenkins ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] atr in dir Vs. hasattr
What is the difference between using hasattr(object, name) and name in dir(object) ? TIA -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] atr in dir Vs. hasattr
On Tue, Mar 15, 2011 at 8:00 PM, Tim Johnson t...@johnsons-web.com wrote: What is the difference between using hasattr(object, name) and name in dir(object) hasattr is basically try: object.name return True except AttributeError: return False while name in dir(object) is (AFAIK) more like: for attr in dir(object): if name == attr: return True return False However, rare is the occasion that you should use either of these. If you're doing something like: if hasattr(myobj, 'something'): myobj.something() else: print blah blah blah then what you really should be doing is: try: myobj.something() except AttributeError: print blah blah blah because 1) you avoid the overhead of an extra(?) try-except block, 2) in Python it's EAFP - Easier to Ask Forgivness than Permission, 3) You shouldn't inspect an object to find out what it can do, you should just try it and then handle failures appropriately (at least that's what I've been told). YMMV, objects in mirror are closer than they appear, etc. etc. HTH, Wayne ? TIA -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] first steps
I'm a newbie running my very first module . . . Specs: Mac OSX 10.6.6 Python 3.2 IDLE v 3.2 Tk v 8.5 I saved this module to my desktop # File: chaos.py # A simple program illustrating chaotic behavior. def main(): print(This program illustrates a chaotic function) x = eval(input(Enter a number between 0 and 1: )) for i in range(10): x = 3.9 * x * (1 - x) print(x) main() When I open and run this module in IDLE's shell the application hangs. This can sometimes be 'fixed' by going to Run Check Module and then running the module. But I have a feeling I'm doing something wrong. Is there a better way to import the file into IDLE so I can run it without crashing the app? Also, when it works correctly, IDLE won't run the program again via the chaos.main() statement. I get this: Traceback (most recent call last): File pyshell#1, line 1, in module chaos.main() NameError: name 'chaos' is not defined Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] atr in dir Vs. hasattr
This following post was originally posted to the wrong thread. I am reposting (hopefully correctly) with the first and very succint response. I thing the answer is a revealation to be noted: ## On Tue, Mar 15, 2011 at 8:00 PM, Tim Johnson t...@johnsons-web.com wrote: What is the difference between using hasattr(object, name) and name in dir(object) ## Wayne Werner waynejwer...@gmail.com Replied: ## hasattr is basically try: object.name return True except AttributeError: return False while name in dir(object) is (AFAIK) more like: for attr in dir(object): if name == attr: return True return False However, rare is the occasion that you should use either of these. If you're doing something like: if hasattr(myobj, 'something'): myobj.something() else: print blah blah blah then what you really should be doing is: try: myobj.something() except AttributeError: print blah blah blah because 1) you avoid the overhead of an extra(?) try-except block, 2) in Python it's EAFP - Easier to Ask Forgivness than Permission, 3) You shouldn't inspect an object to find out what it can do, you should just try it and then handle failures appropriately (at least that's what I've been told). YMMV, objects in mirror are closer than they appear, etc. etc. HTH, Wayne -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] first steps
Hi Ryan, Also, when it works correctly, IDLE won't run the program again via the chaos.main() statement. I get this: Traceback (most recent call last): File pyshell#1, line 1, in module chaos.main() NameError: name 'chaos' is not defined I think IDLE is looking for a file name to run. If your file name is chaos.py, use that. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] first steps
Ryan, Did you enter it like this at the prompt: chaos.main() statement If so, that's a problem. Your function was called: main(), so if you type chaos.main(), Python doesn't know what you're talking about. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Boolean question
On Wed, Mar 16, 2011 at 12:22 AM, Donald Bedsole drbeds...@gmail.comwrote: not (False and True) Python evaluates it as True Is it because: 1)You evaluate what's in the parentheses first. A thing can not be false and true at the same time, so the answer is false. Yes, the expression in the parenthesis is evaluated first. However it's not just one thing being evaluated. 'and' evaluates one argument at a time and returns immediately if the argument is False. In this case there are 2 distinct 'things'. False and True. False, obviously, evaluates to False, which causes 'and' to stop and return False. This reduces the expression to... not False 2)However, the not outside the parentheses flips the meaning of what is inside the parentheses, so false becomes True. ? Correct, the expression not False evaluates to True. -- Jack Trades Pointless Programming Blog http://pointlessprogramming.wordpress.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor