Litty
Litty

Reputation: 305

python : is decorators for method arguments possible?

Is it possible to decorate method arguments? Something like:

class SampleEntity (BaseEntity) :
    def someOperation (self, @Param(type="int", unit="MB")i, str) :
        pass

Basically I want the developer to be able to specify metadata about the class, properties, methods, arguments etc which I can process later on. For class and methods I could use decorators. So I was wondering how to do it for method arguments.

Thanks, Litty

Upvotes: 3

Views: 211

Answers (5)

Skurmedel
Skurmedel

Reputation: 22159

You can document the function definition with annotations. What the annotations actually mean is up to you and the code using your functions.

For example:

def dostuff(f: str, x: "Hula hula!"):
     pass

Upvotes: 1

Cat Plus Plus
Cat Plus Plus

Reputation: 129894

No, but in Python 3 you can use annotations.

def func(arg: Param(type = 'int', unit = 'MB')):
   pass

Annotations can hold any information you want, language doesn't define what should go there. You can access them with func.__annotations__ dict later.

Upvotes: 8

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72795

If it's for documentation, you might be able to use the docstring conventions which are commonly used.

If it's for more concrete information that you can later use in your apps, you might be able to use enthought traits.

If you want static typing, you should use a different language.

Upvotes: 4

David Heffernan
David Heffernan

Reputation: 613262

You can't place the decorator in the parameter list, it has to be around the function or class.

You might want to use an existing decorator as the starting point for your decorator.

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363737

No. You can decorate functions and classes, but not parameters.

Upvotes: 3

Related Questions