Talin wrote: [...] > For example, the suggestion of testing each member of a module with > "is_module" is fine - except that a newbie programmer's first attempt to > write "is_module" is probably going to be "isinstance( value, module )" > which won't work because the word "module" isn't bound to a type. > At which point, they will have to go digging through the library docs to > figure out where the standard types live, or if there's some other way > to determine if an object is a module or not.
Well, a general trick to find a type, assuming you can get an instance is, unsuprisingly, to use type(). For instance: import sys modtype = type(sys) def ismodule(obj): return isinstance(obj, modtype) That said, depending on your application, this might actually be better implemented, although it's a bit slower, as: def ismodule(obj): return (obj in sys.modules.values()) It's not unheard of for people to stuff things other than modules into sys.modules in order to pursue their devious ends. Probably the less said about that the better though. Anyway, finding out what is a module and what is not is a bit tricky, and depends a bit on what you are trying to do, but that seems a rather specialized application. For this kind of question you can always ask on c.l.python. I bet you'd get dozens of answers and no more than half of them would be wrong ;) [...] > > The same is true for the problem of a "plugins" dir containing modules > to import. Yes, its only 3 lines of code to list the directory and import > each file - but coming up with those exact 3 lines (in particular, getting > the arguments to __import__ correct) is trickier than it looks, especially > when you are trying not to hard-code the module name. What I came > up with is this, which is probably incorrect: > > # Import all parsers > dirname = os.path.dirname( __file__ ) > for name in os.listdir( dirname ): > if fnmatch.fnmatch( name, "*.py" ) and name != "__init__.py": > mod = __import__( "%s.%s" % ( __name__, os.path.splitext( name )[ 0 ] > ) ) Yes, __import__ can be tricky. You might want to look at imp.load_source instead. I don't use that stuff enough to toss off the correct incantation off the top of my head, but I think that would likely be cleaner. > Perhaps the answer is better docs? For example, there's a number of > docs on the package / module loading mechanism, but they all seem > like pieces of an incomplete puzzle to me. There's always room for better docs or perhaps domain specific tutorials. I don't know if that's really a Python 3000 issue, doc improvement should be an ongoing process. Regards, -tim _______________________________________________ Python-3000 mailing list Python-3000@python.org http://mail.python.org/mailman/listinfo/python-3000 Unsubscribe: http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com