Gustavo Picon avatar Gustavo Picon committed 31dbf1a

Cleanup: Pycharm autorefactoring

Comments (0)

Files changed (14)

 templates_path = ['_templates']
 source_suffix = '.rst'
 master_doc = 'index'
-project = u'django-treebeard'
-copyright = u'2008-2010, Gustavo Picon'
+project = 'django-treebeard'
+copyright = '2008-2010, Gustavo Picon'
 version = '2.0a1'
 release = '2.0a1'
 exclude_trees = ['_build']
 html_static_path = ['_static']
 htmlhelp_basename = 'django-treebearddoc'
 latex_documents = [
-  ('index', 'django-treebeard.tex', u'django-treebeard Documentation',
-   u'Gustavo Picon', 'manual')]
+  ('index', 'django-treebeard.tex', 'django-treebeard Documentation',
+   'Gustavo Picon', 'manual')]

treebeard/admin.py

-"Django admin support for treebeard"
+"""Django admin support for treebeard"""
 
 import sys
 
-from django.conf.urls.defaults import patterns, url
+from django.conf.urls import patterns, url
 from django.contrib import admin, messages
 from django.contrib.admin.views.main import ChangeList
 from django.http import HttpResponse, HttpResponseBadRequest
 
 
 class TreeAdmin(admin.ModelAdmin):
-    "Django Admin class for treebeard"
+    """Django Admin class for treebeard"""
     change_list_template = 'admin/tree_change_list.html'
     form = MoveNodeForm
 

treebeard/al_tree.py

-"Adjacency List"
+"""Adjacency List"""
 
 from django.core import serializers
 from django.db import connection, models, transaction
 
 
 class AL_NodeManager(models.Manager):
-    "Custom manager for nodes."
+    """Custom manager for nodes."""
 
     def get_query_set(self):
-        "Sets the custom queryset as the default."
+        """Sets the custom queryset as the default."""
         qset = super(AL_NodeManager, self).get_query_set()
         if self.model.node_order_by:
             order_by = ['parent'] + list(self.model.node_order_by)
 
 
 class AL_Node(Node):
-    "Abstract model to create your own Adjacency List Trees."
+    """Abstract model to create your own Adjacency List Trees."""
 
     objects = AL_NodeManager()
     node_order_by = None
 
     @classmethod
     def add_root(cls, **kwargs):
-        "Adds a root node to the tree."
+        """Adds a root node to the tree."""
         newobj = cls(**kwargs)
         newobj._cached_depth = 1
 
 
     @classmethod
     def get_root_nodes(cls):
-        ":returns: A queryset containing the root nodes in the tree."
+        """:returns: A queryset containing the root nodes in the tree."""
         return cls.objects.filter(parent__isnull=True)
 
     def get_depth(self, update=False):
         return depth
 
     def get_children(self):
-        ":returns: A queryset of all the node's children"
+        """:returns: A queryset of all the node's children"""
         return self.__class__.objects.filter(parent=self)
 
     def get_parent(self, update=False):
-        ":returns: the parent node of the current node object."
+        """:returns: the parent node of the current node object."""
         return self.parent
 
     def get_ancestors(self):
         return ancestors
 
     def get_root(self):
-        ":returns: the root node for the current node object."
+        """:returns: the root node for the current node object."""
         ancestors = self.get_ancestors()
         if ancestors:
             return ancestors[0]
 
     @classmethod
     def dump_bulk(cls, parent=None, keep_ids=True):
-        "Dumps a tree branch to a python data structure."
+        """Dumps a tree branch to a python data structure."""
 
         serializable_cls = cls._get_serializable_model()
         if (
         return ret
 
     def add_child(self, **kwargs):
-        "Adds a child to the node."
+        """Adds a child to the node."""
         newobj = self.__class__(**kwargs)
         try:
             newobj._cached_depth = self._cached_depth + 1
         return self.__class__.get_tree(parent=self)[1:]
 
     def get_descendant_count(self):
-        ":returns: the number of descendants of a nodee"
+        """:returns: the number of descendants of a nodee"""
         return len(self.get_descendants())
 
     def get_siblings(self):
         return self.__class__.get_root_nodes()
 
     def add_sibling(self, pos=None, **kwargs):
-        "Adds a new node as a sibling to the current node object."
+        """Adds a new node as a sibling to the current node object."""
 
         pos = self._fix_add_sibling_opts(pos)
 
         transaction.commit_unless_managed()
 
     class Meta:
-        "Abstract model."
+        """Abstract model."""
         abstract = True

treebeard/exceptions.py

-"Treebeard exceptions"
+"""Treebeard exceptions"""
 
 
 class InvalidPosition(Exception):
-    "Raised when passing an invalid pos value"
+    """Raised when passing an invalid pos value"""
 
 
 class InvalidMoveToDescendant(Exception):
-    "Raised when attemping to move a node to one of it's descendants."
+    """Raised when attemping to move a node to one of it's descendants."""
 
 
 class MissingNodeOrderBy(Exception):

treebeard/forms.py

-"Forms for treebeard."
+"""Forms for treebeard."""
 
 from django import forms
 from django.db.models.query import QuerySet
             else:
                 prev_sibling = instance.get_prev_sibling()
                 if prev_sibling is None:
-                    if (instance.is_root()):
+                    if instance.is_root():
                         object_data.update({
                             '_ref_node_id': '',
                             '_position': 'first-child',

treebeard/models.py

-"Models and base API"
+"""Models and base API"""
 
 import sys
 import operator
 
 from django.db.models import Q
 from django.db import models, transaction, router, connections
-from django.conf import settings
 
 from treebeard.exceptions import InvalidPosition, MissingNodeOrderBy
 
 
 class Node(models.Model):
-    "Node class"
+    """Node class"""
 
     _db_vendor = None
 
 
     @classmethod
     def get_root_nodes(cls):  # pragma: no cover
-        ":returns: A queryset containing the root nodes in the tree."
+        """:returns: A queryset containing the root nodes in the tree."""
         raise NotImplementedError
 
     @classmethod
     def get_first_root_node(cls):
-        ":returns: The first root node in the tree or ``None`` if it is empty"
+        """
+        :returns:
+
+            The first root node in the tree or ``None`` if it is empty.
+        """
         try:
             return cls.get_root_nodes()[0]
         except IndexError:
 
     @classmethod
     def get_last_root_node(cls):
-        ":returns: The last root node in the tree or ``None`` if it is empty"
+        """
+        :returns:
+
+            The last root node in the tree or ``None`` if it is empty.
+        """
         try:
             return cls.get_root_nodes().reverse()[0]
         except IndexError:
 
     @classmethod
     def find_problems(cls):  # pragma: no cover
-        "Checks for problems in the tree structure."
+        """Checks for problems in the tree structure."""
         raise NotImplementedError
 
     @classmethod
         return nodes
 
     def get_depth(self):  # pragma: no cover
-        ":returns: the depth (level) of the node"
+        """:returns: the depth (level) of the node"""
         raise NotImplementedError
 
     def get_siblings(self):  # pragma: no cover
         raise NotImplementedError
 
     def get_children(self):  # pragma: no cover
-        ":returns: A queryset of all the node's children"
+        """:returns: A queryset of all the node's children"""
         raise NotImplementedError
 
     def get_children_count(self):
-        ":returns: The number of the node's children"
+        """:returns: The number of the node's children"""
 
         # this is the last resort, subclasses of Node should implement this in
         # a efficient way.
         raise NotImplementedError
 
     def get_descendant_count(self):
-        ":returns: the number of descendants of a node."
+        """:returns: the number of descendants of a node."""
         return self.get_descendants().count()
 
     def get_first_child(self):
-        ":returns: The leftmost node's child, or None if it has no children."
+        """
+        :returns:
+
+            The leftmost node's child, or None if it has no children.
+        """
         try:
             return self.get_children()[0]
         except IndexError:
             return None
 
     def get_last_child(self):
-        ":returns: The rightmost node's child, or None if it has no children."
+        """
+        :returns:
+
+            The rightmost node's child, or None if it has no children.
+        """
         try:
             return self.get_children().reverse()[0]
         except IndexError:
         raise NotImplementedError
 
     def get_root(self):  # pragma: no cover
-        ":returns: the root node for the current node object."
+        """:returns: the root node for the current node object."""
         raise NotImplementedError
 
     def is_root(self):
-        ":returns: True if the node is a root node (else, returns False)"
+        """:returns: True if the node is a root node (else, returns False)"""
         return self.get_root() == self
 
     def is_leaf(self):
-        ":returns: True if the node is a leaf node (else, returns False)"
+        """:returns: True if the node is a leaf node (else, returns False)"""
         return self.get_children_count() == 0
 
     def get_ancestors(self):  # pragma: no cover
         raise NotImplementedError
 
     def delete(self):
-        "Removes a node and all it's descendants."
+        """Removes a node and all it's descendants."""
         self.__class__.objects.filter(id=self.pk).delete()
 
     def _fix_add_sibling_opts(self, pos):
-        "prepare the pos variable for the add_sibling method"
+        """prepare the pos variable for the add_sibling method"""
         if pos is None:
             if self.node_order_by:
                 pos = 'sorted-sibling'
         return pos
 
     def _fix_move_opts(self, pos):
-        "prepare the pos var for the move method"
+        """prepare the pos var for the move method"""
         if pos is None:
             if self.node_order_by:
                 pos = 'sorted-sibling'
             if start_depth is None:
                 start_depth = depth
 
-            open = (depth  and (prev_depth is None or depth > prev_depth))
+            open = (depth and (prev_depth is None or depth > prev_depth))
 
             if prev_depth is not None and depth < prev_depth:
                 info['close'] = list(range(0, prev_depth - depth))
 
         (this is a workaround for a bug in django)
         """
-        while cls._meta.proxy:
-            cls = cls._meta.proxy_for_model
-        return cls
+        current_class = cls
+        while current_class._meta.proxy:
+            current_class = current_class._meta.proxy_for_model
+        return current_class
 
     @classmethod
     def get_database_vendor(cls, action):
         return cls._db_vendor[action]
 
     class Meta:
-        "Abstract model."
+        """Abstract model."""
         abstract = True

treebeard/mp_tree.py

-"Materialized Path Trees"
+"""Materialized Path Trees"""
 
 import sys
 import operator
 
 
 class MP_NodeManager(models.Manager):
-    "Custom manager for nodes."
+    """Custom manager for nodes."""
 
     def get_query_set(self):
-        "Sets the custom queryset as the default."
+        """Sets the custom queryset as the default."""
         return MP_NodeQuerySet(self.model).order_by('path')
 
 
 class MP_Node(Node):
-    "Abstract model to create your own Materialized Path Trees."
+    """Abstract model to create your own Materialized Path Trees."""
 
     steplen = 4
     alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 
     @classmethod
     def dump_bulk(cls, parent=None, keep_ids=True):
-        "Dumps a tree branch to a python data structure."
+        """Dumps a tree branch to a python data structure."""
 
         # Because of fix_tree, this method assumes that the depth
         # and numchild properties in the nodes can be incorrect,
 
     @classmethod
     def get_root_nodes(cls):
-        ":returns: A queryset containing the root nodes in the tree."
+        """:returns: A queryset containing the root nodes in the tree."""
         return cls.objects.filter(depth=1)
 
     @classmethod
         return ret
 
     def get_depth(self):
-        ":returns: the depth (level) of the node"
+        """:returns: the depth (level) of the node"""
         return self.depth
 
     def get_siblings(self):
         return qset
 
     def get_children(self):
-        ":returns: A queryset of all the node's children"
+        """:returns: A queryset of all the node's children"""
         if self.is_leaf():
             return self.__class__.objects.none()
         return self.__class__.objects.filter(
         return newobj
 
     def get_root(self):
-        ":returns: the root node for the current node object."
+        """:returns: the root node for the current node object."""
         return self.__class__.objects.get(path=self.path[0:self.steplen])
 
     def get_ancestors(self):
 
     @classmethod
     def _get_basepath(cls, path, depth):
-        ":returns: The base path of another path up to a given depth"
+        """:returns: The base path of another path up to a given depth"""
         if path:
-            return path[0:(depth) * cls.steplen]
+            return path[0:depth * cls.steplen]
         return ''
 
     @classmethod
 
     @classmethod
     def _inc_path(cls, path):
-        ":returns: The path of the next sibling of a given node path."
+        """:returns: The path of the next sibling of a given node path."""
         newpos = cls._str2int(path[-cls.steplen:]) + 1
         key = cls._int2str(newpos)
         if len(key) > cls.steplen:
 
     @classmethod
     def _get_lastpos_in_path(cls, path):
-        ":returns: The integer value of the last step in a path."
+        """:returns: The integer value of the last step in a path."""
         return cls._str2int(path[-cls.steplen:])
 
     @classmethod
     def _get_parent_path_from_path(cls, path):
-        ":returns: The parent path for a given path"
+        """:returns: The parent path for a given path"""
         if path:
             return path[0:len(path) - cls.steplen]
         return ''
 
     @classmethod
     def _get_children_path_interval(cls, path):
-        ":returns: An interval of all possible children paths for a node."
+        """:returns: An interval of all possible children paths for a node."""
         return (path + cls.alphabet[0] * cls.steplen,
                 path + cls.alphabet[-1] * cls.steplen)
 
         return oldpath, newpath
 
     def _fix_move_to_child(self, pos, target):
-        "Update preliminar vars in :meth:`move` when moving to a child"
+        """Update preliminar vars in :meth:`move` when moving to a child"""
         newdepth = target.depth
         newpos = None
         siblings = []
 
     @classmethod
     def _get_sql_update_numchild(cls, path, incdec='inc'):
-        ":returns: The sql needed the numchild value of a node"
+        """:returns: The sql needed the numchild value of a node"""
         sql = "UPDATE %s SET numchild=numchild%s1"\
               " WHERE path=%%s" % (
                   connection.ops.quote_name(cls._meta.db_table),
         return sql, vals
 
     class Meta:
-        "Abstract model."
+        """Abstract model."""
         abstract = True

treebeard/ns_tree.py

-"Nested Sets"
+"""Nested Sets"""
 
 import sys
 import operator
     """
 
     def get_query_set(self):
-        "Sets the custom queryset as the default."
+        """Sets the custom queryset as the default."""
         return NS_NodeQuerySet(self.model).order_by('tree_id', 'lft')
 
 
 class NS_Node(Node):
-    "Abstract model to create your own Nested Sets Trees."
+    """Abstract model to create your own Nested Sets Trees."""
     node_order_by = []
 
     lft = models.PositiveIntegerField(db_index=True)
 
     @classmethod
     def add_root(cls, **kwargs):
-        "Adds a root node to the tree."
+        """Adds a root node to the tree."""
 
         # do we have a root node already?
         last_root = cls.get_last_root_node()
         return sql, []
 
     def add_child(self, **kwargs):
-        "Adds a child to the node."
+        """Adds a child to the node."""
         if not self.is_leaf():
             # there are child nodes, delegate insertion to add_sibling
             if self.node_order_by:
         newobj.rgt = self.lft + 2
 
         # this is just to update the cache
-        self.rgt = self.rgt + 2
+        self.rgt += 2
 
         newobj._cached_parent_obj = self
 
         return newobj
 
     def add_sibling(self, pos=None, **kwargs):
-        "Adds a new node as a sibling to the current node object."
+        """Adds a new node as a sibling to the current node object."""
 
         pos = self._fix_add_sibling_opts(pos)
 
 
     @classmethod
     def load_bulk(cls, bulk_data, parent=None, keep_ids=False):
-        "Loads a list/dictionary structure to the tree."
+        """Loads a list/dictionary structure to the tree."""
 
         # tree, iterative preorder
         added = []
         return added
 
     def get_children(self):
-        ":returns: A queryset of all the node's children"
+        """:returns: A queryset of all the node's children"""
         return self.get_descendants().filter(depth=self.depth + 1)
 
     def get_depth(self):
-        ":returns: the depth (level) of the node"
+        """:returns: the depth (level) of the node"""
         return self.depth
 
     def is_leaf(self):
-        ":returns: True if the node is a leaf node (else, returns False)"
+        """:returns: True if the node is a leaf node (else, returns False)"""
         return self.rgt - self.lft == 1
 
     def get_root(self):
-        ":returns: the root node for the current node object."
+        """:returns: the root node for the current node object."""
         if self.lft == 1:
             return self
         return self.__class__.objects.get(tree_id=self.tree_id, lft=1)
 
     def is_root(self):
-        ":returns: True if the node is a root node (else, returns False)"
+        """:returns: True if the node is a root node (else, returns False)"""
         return self.lft == 1
 
     def get_siblings(self):
 
     @classmethod
     def dump_bulk(cls, parent=None, keep_ids=True):
-        "Dumps a tree branch to a python data structure."
+        """Dumps a tree branch to a python data structure."""
         qset = cls._get_serializable_model().get_tree(parent)
         ret, lnk = [], {}
         for pyobj in qset:
         return self.__class__.get_tree(self).exclude(pk=self.pk)
 
     def get_descendant_count(self):
-        ":returns: the number of descendants of a node."
+        """:returns: the number of descendants of a node."""
         return (self.rgt - self.lft - 1) / 2
 
     def get_ancestors(self):
 
     @classmethod
     def get_root_nodes(cls):
-        ":returns: A queryset containing the root nodes in the tree."
+        """:returns: A queryset containing the root nodes in the tree."""
         return cls.objects.filter(lft=1)
 
     class Meta:
-        "Abstract model."
+        """Abstract model."""
         abstract = True

treebeard/numconv.py

     """
 
     def __init__(self, radix=10, alphabet=BASE85):
-        "basic validation and cached_map storage"
+        """basic validation and cached_map storage"""
         if int(radix) != radix:
             raise TypeError('radix must be an integer')
         if not 2 <= radix <= len(alphabet):
 
 
 def int2str(num, radix=10, alphabet=BASE85):
-    "helper function for quick base conversions from integers to strings"
+    """helper function for quick base conversions from integers to strings"""
     return NumConv(radix, alphabet).int2str(num)
 
 
 def str2int(num, radix=10, alphabet=BASE85):
-    "helper function for quick base conversions from strings to integers"
+    """helper function for quick base conversions from strings to integers"""
     return NumConv(radix, alphabet).str2int(num)

treebeard/static/treebeard/treebeard-admin.js

                 return $elem.clone();
             }
         }
-    }
+    };
 
     $(document).ready(function () {
 
                 $drag_line.remove();
                 $body.enableSelection().unbind('mousemove').unbind('mouseup');
                 node.elem.removeAttribute('style');
-            }
+            };
 
             // Create a clone create the illusion that we're moving the node
             var node = new Node($(this).closest('tr')[0]);

treebeard/templatetags/admin_tree.py

                 else:
                     result_repr = mark_safe(result_repr)
             else:
-                if value is None:
-                    result_repr = EMPTY_CHANGELIST_VALUE
                 if isinstance(f.rel, models.ManyToOneRel):
                     result_repr = escape(getattr(result, f.name))
                 else:
             '<td>%s</td>' % force_str(form[cl.model._meta.pk.name]))
 
 
+def get_parent_id(node):
+    """Return the node's parent id or 0 if node is a root node."""
+    if node.is_root():
+        return 0
+    return node.get_parent().pk
+
+
 def results(cl):
-    parent_id = lambda n: n.get_parent().pk if not n.is_root() else 0
     if cl.formset:
         for res, form in zip(cl.result_list, cl.formset.forms):
-            yield (res.pk, parent_id(res), res.get_depth(),
+            yield (res.pk, get_parent_id(res), res.get_depth(),
                    res.get_children_count(),
                    list(items_for_result(cl, res, form)))
     else:
         for res in cl.result_list:
-            yield (res.pk, parent_id(res), res.get_depth(),
+            yield (res.pk, get_parent_id(res), res.get_depth(),
                    res.get_children_count(),
                    list(items_for_result(cl, res, None)))
 
         'text': '+',
         'sortable': True,
         'url': request.path,
-        'tooltip': _(u'Return to ordered tree'),
+        'tooltip': _('Return to ordered tree'),
         'class_attrib': mark_safe(' class="oder-grabber"')
     })
     return {
 
 
 def get_static_url():
-    "Return a base static url, always ending with a /"
+    """Return a base static url, always ending with a /"""
     path = getattr(settings, 'STATIC_URL', None)
     if not path:
         path = getattr(settings, 'MEDIA_URL', None)

treebeard/templatetags/admin_tree_list.py

 def __subtree(node, request):
     tree = ''
     for subnode in node.get_children():
-        tree = tree + '<li>%s</li>' % __subtree(subnode, request)
+        tree += '<li>%s</li>' % __subtree(subnode, request)
     if tree:
         tree = '<ul>%s</ul>' % tree
     return __line(node, request) + tree
 def result_tree(cl, request):
     tree = ''
     for root_node in cl.model.get_root_nodes():
-        tree = tree + '<li>%s</li>' % __subtree(root_node, request)
+        tree += '<li>%s</li>' % __subtree(root_node, request)
     return "<ul>%s</ul>" % tree

treebeard/tests/settings.py

-"Django settings for testing treebeard"
+"""Django settings for testing treebeard"""
 
 import random
 import string

treebeard/tests/test_treebeard.py

-"Unit/Functional tests"
+"""Unit/Functional tests"""
 
 import os
 import sys
             node = self.sorted_model.objects.get(pk=node.pk)
             target = self.sorted_model.objects.get(pk=target.pk)
 
-            node.val1 = node.val1 - 2
+            node.val1 -= 2
             node.save()
             node.move(target, 'sorted-sibling')
         expected = [(0, 2, 'qwe', 1, 0),
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.