Are Python Decorators the same or similar, or fundamentally different to Java annotations or something like Spring AOP, or Aspect J?
Python decorators and Java Annotations share de same syntax but to two very different purposes! They aren't compatible or interchangeable for none way!
On a recent project, I had the necessity to use the java annotation semantics on a python script, and I searched a way to emulate it and found this:
In Python there are a functionality called 'Docstring'!
It nothing more else than a special comment line that have to be the first line in a module, class or function!
Like a comment line, you can use any form of text. But what make it so special to me in this case is that is readable by python instrospection!!
So it can works like a Java Annotation, that too needs the Java reflection to interpret and react to metadata carryed from it!!
Follow a short example:
Source a.py
```
def some_function():
'''@myJavaLikeAnnotation()'''
... (my function code) ...
```
Source b.py (where I have to process the @myJavaLikeAnnotacion()):
import a
for element_name in dir(a):
element = getattr(a, element_name)
if hasattr(element, '__call__'):
if not inspect.isbuiltin(element):
try:
doc = str(element.__doc__)
if not doc == '@myJavaLikeAnnotation()':
# It don't have the 'java like annotation'!
break
... It have! Do what you have to do...
except:
pass
Obviously that disadvantages is to have to parse by yourself all the metadata that you use in your 'python java like annotations'!