'Set location, checking for loops and allowing dbref'

def __location_set(self, location):

    if isinstance(location, (basestring, int)):
        dbid = dbref(location, reqhash=False)
        if dbid:
            try:
                location = ObjectDB.objects.get(id=dbid)
            except ObjectDoesNotExist:
                pass
    try:
        def is_loc_loop(loc, depth=0):
            'Recursively    traverse    target    location,    trying    to    catch    a    loop.'
            if (depth > 10):
                return None
            elif (loc == self):
                raise RuntimeError
            elif (loc is None):
                raise RuntimeWarning
            return is_loc_loop(loc.db_location, (depth + 1))
        try:
            is_loc_loop(location)
        except RuntimeWarning:
            pass
        old_location = self.db_location
        self._safe_contents_update = True
        self.db_location = location
        self.save(update_fields=['db_location'])
        del self._safe_contents_update
        if old_location:
            old_location.contents_cache.remove(self)
        if self.db_location:
            self.db_location.contents_cache.add(self)
    except RuntimeError:
        errmsg = ('Error:    %s.location    =    %s    creates    a    location    loop.' % (self.key, location))
        raise RuntimeError(errmsg)
    except Exception as e:
        errmsg = ('Error    (%s):    %s    is    not    a    valid    location.' % (str(e), location))
        raise RuntimeError(errmsg)
    return
