Pages

Thursday, April 24, 2014

Python doc generator: sphinx docstring examples











Python: Code completion in pydev








Code Completion

Type hinting with docstrings/comments

New on PyDev 2.8.0

It's possible to provide hints for code-completion with docstrings by commenting types with the Sphinx/Epydoc format.
Below are some examples of how to provide type-hints.

Return type with Sphinx

class MyClass:

    def method(self):
        ':rtype unittest.TestCase'

Parameter type with Sphinx

class MyClass:

    def method(self, a):
        ':type a: TestCase'
        #Note that just the class name is accepted, but in this case,
        #it'll search for a TestCase class in the whole workspace

Parameter type with Sphinx inline

class MyClass:

    def method(self, a):
        ':param TestCase a:'

Local variable with Sphinx

class MyClass:

    def method(self, lst):
        #Can be on the same line
        for a in lst: #: :type a: GUITest
            a.;

Local variable with Sphinx

class MyClass:

    def method(self, lst):
        #Or on the line before
        #: :type a: GUITest
        for a in lst:
            a.;

Local variable with Sphinx

class MyClass:

    def method(self, lst):
        #If commented as a docstring must be on the
        #line after
        for a in lst:
            ': :type a: GUITest'
            a.;

Return type with Epydoc

class MyClass:

    def method(self):
        '@rtype unittest.TestCase'

Parameter type with Epydoc

class MyClass:

    def method(self, a):
        '@type a: TestCase'
        #Note that just the class name is accepted, but in this case,
        #it'll search for a TestCase class in the whole workspace



Saturday, April 19, 2014

Python: equivalent to Java toString()








In Java, overrides toString() method in the your class can change the textual representation of the object. The equivalent in Python is __str__ and __repr__. The important differences are:
  • the goal of __repr__ is to be unambiguous
  • the goal of __str__ is to be human-readable.
  • str(object) calls the object's __str__ method
  • repr(object) calls the object's __repr__ method
  • by default, if __repr__ is defined and __str__ is not, calls to __str__ will be redirected to __repr__
  • __repr__: representation of python object usually eval will convert it back to that object
  • __str__: is whatever you think is that object in text form
  • str(list) calls the list elements' _repr_ methods. Therefore, to make a list of objects human-readable, you need to override __repr__, or use list comprehension like:
    [str(elem) for elem in list]
    ..

see also




Friday, April 18, 2014

Python: module file name conflicts with the package name








I have a python module file named xml.py, in the module
import xml.etree.ElementTree as ET
... ...
When executing the file, it raises the following error:
ImportError: No module named etree.ElementTree
According the stackoverflow post, it was caused by the moudle file name xml.py, rename the xml.py to something else resolved the issue.


Python: ElementTree XML element to string








import xml.etree.ElementTree as ET

# element is an xml.etree.ElementTree.Element object
xmlstr = ET.tostring(element, encoding='utf8', method='xml')


See also




Python: parse xml using ElementTree








  • parse from a file:
    import xml.etree.ElementTree as ET
    tree = ET.parse('/home/wilson/my.xml')
    root = tree.getroot()
    
  • parse from a string:
    import xml.etree.ElementTree as ET
    root = ET.fromstring('1')
    


see also




Python: class method vs static method








class A:
    def object_m(self,x):
        print "executing object_m(%s,%s)"%(self,x)

    @classmethod
    def class_m(cls,x):
        print "executing class_m(%s,%s)"%(cls,x)

    @staticmethod
    def static_m(x):
        print "executing static_m(%s)"%x    

According to stackoverflow:

A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.

A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved.


Python: check argument type








  • for objects:
    def f(arg):
        if isinstance(arg, ClassA):
            print('A')
        elif isintance(arg, ClassB):
            print('B')
        elif issubclass(arg, ClassC):
            print('subclass of C')
        else:
            print("D")
    
  • for built-in types:
    def f(arg):
        if type(arg) is str:
            print "str"
        elif type(arg) is int:
            print "int"
        elif type(arg) is dict:
            print "dict"
        else:
            print "unsupported"
    



Thursday, April 17, 2014

Python: get the sub-elements of a xml element








According to Python XML ElementTree API,
  • get all sub-elements(descendants):
    all_descendants = list(element.iter())
  • get direct sub-elements(children):
    children = list(element)



Python: check if a list is empty








    if not a:
        print('empty')



Python: iterate over dictionary








for name in dict.keys():
    print(name)
    print(dict[name])
values = [ dict[name] for name in dict.keys() ]



Python: list comprehension








  • To transform a list to another:
    list2 = [ unicode(e.strip()) for e in list1 ]
    
  • To transform a list to another conditionally:
    list2 = [ unicode(e.strip()) if e is not None else '' for e in list1 ]