title: Is it possible to implement .NET-like attributes in Python?
body: <p>I'm a big fan of .NETs attributes - pre-defined and user-defined ones. Attributes are classes inherited from <code>Attribute</code>. Mostly everything in .NET (classes, methods, members (properties, fields, enum values)) can be 'decorated'/equipped with attributes. This attributes can be read-back by e.g. the compiler to extract compiler hints or by the user as kind of meta programming.</p>
  
  <p>C# example:</p>
  
  <pre class="lang-cs prettyprint-override"><code>[System.Serializable]
  public class SampleClass {
    // Objects of this type can be serialized.
  }
  </code></pre>
  
  <p>VB example:</p>
  
  <pre class="lang-vb prettyprint-override"><code>&lt;System.Serializable()&gt;
  Public Class SampleClass
    ' Objects of this type can be serialized.
  End Class
  </code></pre>
  
  <p>In my example <code>Serializable</code> marks a class for serialization. A serializer can now retrieve all members of that class' instances and assemble the instance data to a serialized object. It's also possible so mark single fields to be serialized or not.</p>
  
  <p>A user can get defined attributes from a class with the help of reflection: <code>System.Attribute.GetCustomAttributes(...)</code></p>
  
  <p>For further reading (MSDN documentation):<br>
   - <a href="https://msdn.microsoft.com/en-us/library/84c42s56(v=vs.110).aspx" rel="nofollow">Writing Custom Attributes</a><br>
   - <a href="https://msdn.microsoft.com/en-us/library/71s1zwct(v=vs.110).aspx" rel="nofollow">Retrieving Information Stored in Attributes</a></p>
  
  <p>I'm also a big fan of Python and decorators. Is it possible to implement .NET-like attributes in Python with the help of decorators? What would it look like in Python?</p>
  
  <pre class="lang-py prettyprint-override"><code>@Serializable
  class SampleClass():
    # Objects of this type can be serialized.
  </code></pre>
  
  <p>Another use case could be the Python <code>argparse</code> library. It's possible to register callback functions, which are called by sub-parsers if the input contains the correct sub-command. A more natural way to define such command line argument syntax could be the usage of decorators.</p>
  
  <p><strong>This question is not about serialization - it's just an usage example.</strong></p>