0

I'm having some trouble doing this. Currently I have a module which has a bunch of classes in it, some of these classes are going to be decorated to indicate some things.

What I would like is to create a new, fake module which contains only the decorated classes. So something like this:

class FakeModule: pass

def Decorator(cls):
    attr = getattr(RealModule, cls)
    setattr(FakeModule, cls, attr)

Any suggestions? I'm pretty new to python and python decorators so I'm not really sure what the proper way to do this is.

  • 1
    I'm confused by your use of the word "module". And also what you're trying to accomplish. And why. – Colleen Oct 15 '12 at 20:43
  • Basically I have a file with a bunch of test classes. Some of these test classes will be decorated with @Decorator(). Elsewhere I have something like: FunctionWhichDoesStuffWithTestClasses(file_with_classes). What I need to have is file_with_classes to be 'only' the decorated classes, hence why I am trying to dynamically create. – user1161306 Oct 15 '12 at 20:46
  • 1. what do you mean "test" classes-- classes for tests, or more like "practice" classes? 2. I still don't understand what you're trying to accomplish. Have you read any decorator documentation? http://wiki.python.org/moin/PythonDecorators – Colleen Oct 15 '12 at 20:49
  • Sorry they're basically just classes for tests. What I'm trying to accomplish is, based on these decorators some of the test classes should load and others should not... – user1161306 Oct 15 '12 at 20:57
  • read [python decorators explained](http://stackoverflow.com/a/1594484/4279) – jfs Oct 15 '12 at 21:14

1 Answers1

0

What I would like is to create a new, fake module which contains only the decorated classes

if the decorator sets some unique attribute or value on a class then you could get all classes from a module and filter them using inspect module:

def is_decorated_class(cls, _sentinel=object()):
    return (inspect.isclass(cls) and 
            getattr(cls, "some_attr", _sentinel) == value)

name_class_pairs = inspect.getmembers(realmodule, is_decorated_class)
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • I have already done it this way more or less and the issue is that it happens after the fact of decoration. IE. Decorate all classes, set the attribute, and then check the attribute later on and decide to load it. We need it to be at decoration time (ie. add the class in question in the decorator method itself) – user1161306 Oct 15 '12 at 21:14
  • @user1161306: just call `setattr(fakemodule, classname, classobject)` in the decorator. – jfs Oct 15 '12 at 21:26