开发者

python : is decorators for method arguments possible?

开发者 https://www.devze.com 2023-03-08 17:21 出处:网络
Is it possible to decorate method arguments? Something like: class SampleEntity (BaseEntity) : def someOperation (self, @Param(type=\"int\", unit=\"MB\")i, str) :

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


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.


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.


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


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消