Any way to loop through object variables?

2008-05-28 Thread Dave Challis
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi,
Just wondering if there's a way to iterate through all variables which
an object has set?

Specifically, I'm using the OptionParser module, which returns an
options object, containing all command line options as object variables.
 I'd like to iterate over these rather than getting at them by name.

Cheers,
Dave
- --
~~
__/|_
 ><>       / o   \/|
  Dave Challis   )><>  \_/\|
[EMAIL PROTECTED](
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIPXpHv26GZvAVVFERAmkaAKDUJuGk8L2nJf8B9b1RaMYpVr9bCwCaAubM
TWdK4AmzAgpKNQxZK3AOB4Q=
=6STh
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Any way to loop through object variables?

2008-05-29 Thread Dave Challis
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Ah thanks, vars(...) was exactly what I was after.  I'd come across
dir() before, but this returns more than I need.

Thanks again,
Dave

Saju Pillai wrote:
> 
> On 28-May-08, at 9:49 PM, Gary Herron wrote:
> 
>> Dave Challis wrote:
>>> Hi,
>>> Just wondering if there's a way to iterate through all variables which
>>> an object has set?
>>>
>>> Specifically, I'm using the OptionParser module, which returns an
>>> options object, containing all command line options as object variables.
>>> I'd like to iterate over these rather than getting at them by name.
>>>
>>> Cheers,
>>> Dave
>>
>> For this object (and many others), you can get at the attributes with
>> the vars(...) builtin.
>> It returns a dictionary of attribute names and values.
> 
> 
> Also dir(object) will get you the list of attributes of that object.
> 
> -srp
> 
>>
>>
>> Gary Herron
>>
>>
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list


- --
~o
.
<><   (
 )Dave Challis ><>   ))
_([EMAIL PROTECTED]((___
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIPowrv26GZvAVVFERApQfAJ96bFa1wl1sbnDCNmbtf5/tpNqTaQCdHKwf
k8+Uv8yXn2Bh5ri6sf5qMmA=
=cnfO
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Automatically loading and initialising objects from a plugins directory

2008-07-22 Thread Dave Challis
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

I'm trying to write some code which:
1. Finds all modules in a plugin directory
2. Imports those modules
3. Creates an instance of each object defined in the module (each module
will contain exactly 1 object, which is a subclass of 'Plugin')

The closest I've come so far is with something like:

In plugin.py:
# taken from http://docs.python.org/lib/built-in-funcs.html
def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod

def import_plugins():
mods = []
for filename in os.listdir('/plugins'):
if filename.endswith('.py'):
name = os.path.splitext(filename)[0]
mods.append(my_import('plugins.' + name))
return mods

class Plugin(object):
pass


In plugins/exampleplugin.py:
class ExamplePlugin(Plugin):
def __init__(self):
pass


Calling import_plugins() then gives me a list containing references to
modules.

How can I loop through that list and create an instance of whatever
object was defined within the module? (In this case I'd want to
construct an instance of ExamplePlugin)

Thanks in advance,
Dave


- --
~~

  (
  Dave Challis) ><>
[EMAIL PROTECTED](___
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIhb/Uv26GZvAVVFERAsGaAJ9KwtFI9yXdk2gBGxy0/bjCd5318wCgsiV9
m14BZSvxqZ1EP0OvaXBZoaw=
=TYlD
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Automatically loading and initialising objects from a plugins directory

2008-07-22 Thread Dave Challis
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Diez B. Roggisch wrote:
> Dave Challis wrote:
> 
>> -BEGIN PGP SIGNED MESSAGE-
>> Hash: SHA1
>>
>> I'm trying to write some code which:
>> 1. Finds all modules in a plugin directory
>> 2. Imports those modules
>> 3. Creates an instance of each object defined in the module (each module
>> will contain exactly 1 object, which is a subclass of 'Plugin')
>>
>> The closest I've come so far is with something like:
>>
>> In plugin.py:
>> # taken from http://docs.python.org/lib/built-in-funcs.html
>> def my_import(name):
>> mod = __import__(name)
>> components = name.split('.')
>> for comp in components[1:]:
>> mod = getattr(mod, comp)
>> return mod
>>
>> def import_plugins():
>> mods = []
>> for filename in os.listdir('/plugins'):
>> if filename.endswith('.py'):
>> name = os.path.splitext(filename)[0]
>> mods.append(my_import('plugins.' + name))
>> return mods
>>
>> class Plugin(object):
>> pass
>>
>>
>> In plugins/exampleplugin.py:
>> class ExamplePlugin(Plugin):
>> def __init__(self):
>> pass
>>
>>
>> Calling import_plugins() then gives me a list containing references to
>> modules.
>>
>> How can I loop through that list and create an instance of whatever
>> object was defined within the module? (In this case I'd want to
>> construct an instance of ExamplePlugin)
> 
> 
> Like this:
> 
> for name in dir(plugin):
> thing = getattr(plugin, name)
> try:
>if issubclass(thing, Plugin):
>   thing()
> except ValueError: # issubclass sucks
>pass
> 
> Diez

Thanks for that, it helped as a starting point.  I had some trouble with
using issubclass though (issubclass(Plugin, Plugin) returns true), which
was complicating things.

I modified your code to the following instead (which may well have it's
own pitfalls I'm not aware of!):

for name in dir(plugin):
thing = getattr(plugin, name)
if hasattr(thing, '__bases__') and \
   getattr(thing, '__bases__')[0] == Plugin:
thing()

Cheers,
Dave


- --
~~
 ><>   o  )   <><
  .   ((
 )Dave Challis<>< ))  ><>
_([EMAIL PROTECTED]((__
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIhge8v26GZvAVVFERAh86AJ91DVYPPZ/1x3rjoezFL1P5FXuHNwCZAXdr
DgjzmTNV1/H8vcQ/2Hax3js=
=ZAtM
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Automatically loading and initialising objects from a plugins directory

2008-07-25 Thread Dave Challis
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Fredrik Lundh wrote:
> so now you're no longer supporting mixins and multiple-level
> inheritance?  why not just tweak Diez' example a little:
> 
> for name in dir(plugin):
> 
> thing = getattr(plugin, name)
> 
> # make sure this is a plugin
> try:
>if thing is Plugin:
>continue
>if not issubclass(thing, Plugin):
>continue
> except ValueError: # issubclass sucks
>continue # not a class
> 
> thing() # probably needs error handling around this
> 
> (I also moved the thing call out of the thing validation part, to allow
> you to distinguish between ValueErrors caused by issubclass and errors
> caused by things)
> 
> (btw, another approach would be to use a metaclass to make Plugin
> classes register themselves on import)
> 
> 

Thanks, that works much better.  I've only been using python a couple of
months, so still getting to grips with how it treats classes/subclasses.

I'll have a look into metaclasses too, haven't stumbled upon those yet
at all.

Cheers,
Dave

- --
~~~~~~
  )<><
 <><  (
  Dave Challis)
[EMAIL PROTECTED](___
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIibiHv26GZvAVVFERAgcmAJ4tmC7jp6TTb3Dx2Lw+rKSmJkcSLQCfYFsA
e0ZLOf8lQXhqHcz/Me8ok0E=
=Qcg7
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list