Re: Learning Python for no reason
John Salerno wrote: Just something that crosses my mind every time I delve into "Learning Python" each night. Does anyone see any value in learning Python when you don't need to for school, work, or any other reason? I mean, sure, there's value in learning anything at any time, but for something like a programming language, I can't help but feel that I will be mostly unable to use what I learn simply because I have no reason to use it. The *process* of learning is enough fun for me, and every now and then I do find a small use for Python that really pays off, but for the most part I'm wondering what people's thoughts are as far as simply learning it for the sake of learning. Does it seem like a silly endeavor to most people? Did anyone here learn a programming language when you didn't need to? If so, how much and in what capacity did you use it after you learned it? Hopefully this question even makes sense! -- http://mail.python.org/mailman/listinfo/python-list I think almost anyone especially if frequently uses computer could benefit from learning a scripting language. I'm mainly a C and C++ person and most of my programs use it. But when I want to do a simple one-time task or something that will change frequently I'll use a scripting language to quickly get it done, such as extracting information from a web page or whatever. With C, C++, and Python I do just about whatever I want/need, and they can be combined/embedded as well. In general I think that learning some basics of programming can help develop pretty good logic/analytic skills as well, but that's just my opinion. Maybe it's the other way around and logic/analytic skills lead to easily learning programing languages. As for learning for the sake of it, if it's fun I don't see how it could hurt any. Brian Vanderburg II -- http://mail.python.org/mailman/listinfo/python-list
Zipping python modules
I've installed Python 2.5 on MSW and it works. I'm preparing it to run from a thumb drive so I can run applications by dropping them onto the python.exe or from command line/etc. It works but the size is quite large. I've compressed most of the executables with UPX even the dlls under site-packages, but is there a way I could compress the top-level 'lib' directory into a python.zip instead so save some space, and do I need the 'test' directory (which is about 10MB itself)? Brian Vanderburg II -- http://mail.python.org/mailman/listinfo/python-list
Is there an official way to add methods to an instance?
I don't know if this is the correct place to send this question. I've checked out some ways to get this to work. I want to be able to add a new function to an instance of an object. I've tested two different methods that cause problems with 'deleting'/garbage collection (__del__ may never get called), but implemented one sort of hackishly maybe that works find. I'm wondering if there is more of an official way than mine. 1. import new import gc class A: def __del__(x): print "Deleting" def f(x): print x a = A() a.f = new.instancemethod(a,f) a.f() # This works del a # Not what is expected gc.collect() # Works, but __del__ does not get called 2. import gc def addmethod(self,func,name): def wrapper(*args,**kwargs): return func(self,*args,**kwargs) setattr(self,name,func) class A: def __del__(x): print "Deleting" def f(x): print x a = A() addmethod(a, f, "f") a.f() # Works as expected del a # nope gc.collect() # Still __del__ doesn't get called 3. Slightly hackish method, maybe some problems import gc import weakref def addmethod(self,func,name): # change the value of 'self' so wrapper.func_globals will reference the new value self = weakref.ref(self) def wrapper(*args,**kwargs): return func(self(),*args,**kwargs) setattr(self(),name,func) class A: def __del__(x): print "Deleting" def f(x): print x a = A() addmethod(a, f, "f") a.f() # Works as expected del a gc.collect() With this method 'del a' does the expected most of the time, and "Deleting" does get printed or when calling 'gc.collect()' it prints correctly. This seems the best approach so that when 'a' is no longer valid, the object can die instead of continuing to exitng because wrapper.func_globals still contains a reference, but seems very hackish an maybe problematic. I'm wondering if there is a better way? Brian Vanderburg II -- http://mail.python.org/mailman/listinfo/python-list
Re: Java or C++?
> My idea, if you really love Python and never think about erasing it > from your mind, go for C (not C++). A script language plus C can solve > every problem you need to solve. Also Python works pretty fine with C. I agree mostly with this one. Scripting is very nice when writing an application especially one that needs to change very often. Plus there are several toolkits and existing libraries available for Python. I've used wxPython some with it, and it came in handy for a few applications that I would have normally written in C++/wxWidgets and have to recompile every few weeks to suit my needs (data extraction tools/etc) However there are cases when a compiled language is better, especially anything that needs to be 'fast' and have a lower overhead. I wouldn't use Python to create a very graphics intensive game or anything, though it can be used with pygame/PyOpenGL for some nice simple stuff. Also everything in Python is an object so it can start to consume memory when handling very large data sets. And since there is no guarantee of when garbage collection occurs, simply 'deleting' an item does not ensure it is completely gone, especially if there are cyclic references, though that can be handled by using 'gc.collect()'. I consider C++ just a simplification of C, in the sense that it makes it easier to do things that would take more work to be done in C. One can still use C++ without all of the more complicated aspects but still take advantages of other aspects. C has the advantage that it does not to anything behind your back. This is very useful especially for any form of system development or where you must know exactly what is going on. It is still possible to do 'object oriented' development in C, it just requires some more typing to set up whatever is needed. Even things like COM for windows can be done in C, it just requires manually building the 'vtable' so to speak. Also, C seems to avoid the use of temporaries where as C++ can use them in conversions and assignments automatically if needed. C++ makes some of it easier by doing certain things for you. Take a string object for example. In C, assignment would only do a memory copy operation: String a, b; b = a; The statement 'b = a' would only copy the memory and pointers from 'b' to 'a' which means they would both point to the same buffer. To avoid this, a copy constructor or assignment operator can be implemented when using C++. The same in C would be something like: String_Assign(&b, &a); /* instead of b = a */ Then if a structure contains objects, more work is needed. For example, in C: typedef struct Name { String honorary; String first; String middle; String last; String lineage; } Name; void Name_Create(Name* name) { String_Create(&name->honorary); String_Create(&name->first); String_Create(&name->middle); String_Create(&name->last); String_Create(&name->lineage); } void Name_Assign(Name* self, Name* other) { String_Assign(&self->honorary, &other->honorary); String_Assign(&self->first, &other->first); String_Assign(&self->middle, &other->middle); String_Assign(&self->last, &other->last); String_Assign(&self->lineage, &other->lineage); } Name p1, p2; Name_Create(&p1); Name_Create(&p2); Name_Assign(&p2, &p1); But in C++, this is no problem: Name p1, p2; p2 = p1; This will automatically call the constructors of any contained objects to initialize the string. The implicit assignment operator automatically performs the assignment of any contained objects. Destruction is also automatic. When 'p1' goes out of scope, during the destructor the destructor for all contained objects is called. And if you want more control you can implement the default and copy constructors, destructor, and assignment operator, and tell them to do what you want. Just beware because the explicit constructors only calls default constructors of any parent classes (even the copy constructor) unless an initializer list is used, and an explicit assignment will not automatically do assignment of parent classes. Neither C nor C++ is really better, it depends on the what needs to be done. C does only what it is told, and also has easier external linkage since there is no name mangling. C++ does a lot of the needed stuff automatically, but explicit constructors and assignment operators can still be declared to control them, and frequently doing the same thing in C++ takes fewer lines of code than in C. As for Java, I think it is 'overly-used' in some areas, especially in embedded development. I attended NC State and during orientation this representative was talking about a small little robotic device and how it had a full Java VM inside it and it only took '6 minutes to boot'. Some claim it is for portability that Java is so good in embedded devices. But still, if the program is moved to another device, it may still need to b
Is massive spam coming from me on python lists?
I've recently gotten more than too many spam messages and all say Sender: [EMAIL PROTECTED] I'm wondering if my mail list registration is now being used to spam myself and others. If so, sorry, but I'm not the one sending messages if other are getting them even though Sender seems to include my address (I'm not sure about mail headers so I don't know how From: is different than Sender:) Anyway, it seems to be a bunch of spam emails about cracks and stuff. Brian Vanderburg II -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to store config or preferences in a multi-platform way.
Lance Gamet wrote: Hi, python beginner starting a new project here. This project will store most of its actual data in a shared-database, but I have a small amount of user specific data that I need to be stored like configuration or preferences for example, the list of databases that the program should connect to. On Unix this might be a .file, on windows this could be in the registry, or an ini file or an xml file in ProgramData or AppData or something. Is there a pythony way to store such config data, perhaps there is already a standard python package for such a purpose? My app uses Qt, and Qt has its method of doing it (QSettings), but for architectural reasons I don't want to use it. Could sqlite be an option perhaps? I am still undecided if the ability for the user to edit the file independently of the program is a good or bad thing. Thanks a lot. Lance -- http://mail.python.org/mailman/listinfo/python-list Lance Gamet wrote: Hi, python beginner starting a new project here. This project will store most of its actual data in a shared-database, but I have a small amount of user specific data that I need to be stored like configuration or preferences for example, the list of databases that the program should connect to. On Unix this might be a .file, on windows this could be in the registry, or an ini file or an xml file in ProgramData or AppData or something. Is there a pythony way to store such config data, perhaps there is already a standard python package for such a purpose? My app uses Qt, and Qt has its method of doing it (QSettings), but for architectural reasons I don't want to use it. Could sqlite be an option perhaps? I am still undecided if the ability for the user to edit the file independently of the program is a good or bad thing. Thanks a lot. Lance -- http://mail.python.org/mailman/listinfo/python-list One way I've just started to use it to create a utility function to return the location of the user data folder, depending on the operating system: import os, sys def GetUserDataDirectory(): dir = None # WINDOWS if os.name == "nt": # Try env APPDATA or USERPROFILE or HOMEDRIVE/HOMEPATH if "APPDATA" in os.environ: dir = os.environ["APPDATA"] if ((dir is None) or (not os.path.isdir(dir))) and ("USERPROFILE" in os.environ): dir = os.environ["USERPROFILE"] if os.path.isdir(os.path.join(dir, "Application Data")): dir = os.path.join(dir, "Application Data")) if ((dir is None) or (not os.path.isdir(dir))) and ("HOMEDRIVE" in os.environ) and ("HOMEPATH" in os.environ): dir = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] if os.path.isdir(os.path.join(dir, "Application Data")): dir = os.path.join(dir, "Application Data")) if (dir is None) or (not os.path.isdir(dir)) dir = os.path.expanduser("~") # One windows, add vendor and app name dir = os.path.join(dir, "vendor", "app") # Mac elif os.name == "mac": # ?? may not be entirely correct dir = os.path.expanduser("~") dir = os.path.join(dir, "Library", "Application Support") dir = os.path.join(dir, "vendor", "app") # Unix/Linux/all others else: dir = os.path.expanduser("~") dir = os.path.join(dir, ".app") # Some applications include vendor # dir = os.path.join(dir, ".vendor", "app") return dir Brian Vanderburg II -- http://mail.python.org/mailman/listinfo/python-list
Signals/Slots support in Python
I don't know if any such support is already built in, so I ended up making my own simple signals/slots like mechanism. If anyone is interested then here it is, along with a simple test. It can connect to normal functions as well as instance methods. It also supports weak connections where when an object is gone, the slot is gone as well, the slot just holds a weak reference to the object. Brian Vanderburg II # Begin Signal import weakref import random class Signal: class Slot: def __init__(self, fn): self.__fn = fn def __call__(self, accum, *args, **kwargs): result = self.__fn(*args, **kwargs) return accum(result) class WeakSlot: def __init__(self, conn, parent, fn, obj): self.__conn = conn # Avoid circular references so deleting a signal will # allow deletion of the signal since the slot doesn't ref # back to it but only weakefs back to it self.__parent = weakref.ref(parent) self.__fn = fn self.__obj = weakref.ref(obj, self.Cleanup) def __call__(self, accum, *args, **kwargs): obj = self.__obj() if obj is None: return True result = self.__fn(obj, *args, **kwargs) return accum(result) def Cleanup(self, ref): parent = self.__parent() if parent is not None: parent.Disconnect(self.__conn) class Accumulator: def __call__(self, *args, **kwargs): return True def Finalize(self): return None def __init__(self): self.__slots = [ ] # This connects a signal to a slot, but stores a strong reference so # The object will not be deleted as long as the signal is connected def Connect(self, fn): conn = self.NewConn() self.__slots.append([conn, Signal.Slot(fn)]) return conn # This connects a signal to a slot, but store a weak reference so # when the object is gone the slot will not be called. Because of # the implemenations, it is not possible to do WeakConnect(obj.Fn), # since obj.Fn is a new object and would go to 0 refcount soon after # the call to WeakConnect completes. Instead we must do a call as # WeakConnect(ObjClass.Fn, obj) # Only the object is weak-referenced. The function object is still # a normal reference, this ensures that as long as the object exists # the function will also exist. When the object dies, the slot will # be removed def WeakConnect(self, fn, obj): conn = self.NewConn() self.__slots.append([conn, Signal.WeakSlot(conn, self, fn, obj)]) return conn # Disconnect a slot def Disconnect(self, conn): result = self.Find(conn) if result >= 0: del self.__slots[result] # Disconnect all slots def DisconnectAll(self): self.__slots = [ ] # Create an accumulator. Accumulator will be called as a callable # for each return value of the executed slots. Execution of slots # continues as long as the reutrn value of the accumulator call is # True. The 'Finalize'function will be called to get the result # A custom accumulator can be created by deriving from Signal and # Creating a custom 'Accumulator' class, or by deriving from Singal # and creating CreateAccumulator def CreateAccumulator(self): return self.Accumulator() # Execute the slots def __call__(self, *args, **kwargs): accum = self.CreateAccumulator() for conn in xrange(len(self.__slots)): if not self.__slots[conn][1](accum, *args, **kwargs): break return accum.Finalize() # Create a connection name def NewConn(self): value = 0 while self.Find(value) >= 0: value = random.randint(1, 1) return value def Find(self, conn): for i in xrange(len(self.__slots)): if self.__slots[i][0] == conn: return i return -1 # End Signal def fn1(): print "Hello World" def fn2(): print "Goodbye Space" class O: def __init__(self, value): self.value = value def Action(self): print "O %d" % self.value a = Signal() a.Connect(fn1) a.Connect(fn2) print "Part 1" a() a.DisconnectAll() o1 = O(4) o2 = O(12) a.WeakConnect(O.Action, o1) a.Connect(o2.Action) print "Part 2" a() print "Part 3" o1 = None a() print "Part 4" o2 = None a() a.DisconnectAll() def f1(): print "Hello Neighbor" def f2(): print "Back to Work" c1 = a.Connect(f1) c2
Re: #!/usr/bin/env python vs. #!/usr/bin/python
This is sort of related, but I'm wondering what is different between "#!/usr/bin/env python" and "#!python". Wouldn't the second do the same thing, since an absolute path is not specified, find 'python' from the PATH environment, I don't really know. Brian Vanderburg II -- http://mail.python.org/mailman/listinfo/python-list
Re: #!/usr/bin/env python vs. #!/usr/bin/python
D'Arcy J.M. Cain wrote: On Thu, 08 May 2008 07:31:17 -0400 Brian Vanderburg II <[EMAIL PROTECTED]> wrote: This is sort of related, but I'm wondering what is different between "#!/usr/bin/env python" and "#!python". Wouldn't the second do the same thing, since an absolute path is not specified, find 'python' from the PATH environment, I don't really know. Well, I know what happened when I tried it. What happened when you tried it? I haven't tried it but I've seen some files like written that in the past with just a name and no path for some other interpreter (perl or sh probably) and didn't know what the different was or if it was even valid. I at a windows system now so I can't try it yet. Brian Vanderburg II -- http://mail.python.org/mailman/listinfo/python-list