diff options
| author | Brian Jarrett <celttechie@gmail.com> | 2014-07-10 16:28:49 -0600 |
|---|---|---|
| committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2014-07-13 20:10:55 -0400 |
| commit | 28dd15081db4b7e978fa7a187c3aef1c0e4ad4e3 (patch) | |
| tree | af5aeebb0cece4afc8e12e3329d3f75715bf32a2 /lib/sqlalchemy/ext/declarative | |
| parent | 0190ede10767ed455255067cac2d309f070cf70c (diff) | |
| download | sqlalchemy-28dd15081db4b7e978fa7a187c3aef1c0e4ad4e3.tar.gz | |
PEP8 style fixes
Diffstat (limited to 'lib/sqlalchemy/ext/declarative')
| -rw-r--r-- | lib/sqlalchemy/ext/declarative/__init__.py | 16 | ||||
| -rw-r--r-- | lib/sqlalchemy/ext/declarative/api.py | 31 | ||||
| -rw-r--r-- | lib/sqlalchemy/ext/declarative/base.py | 112 | ||||
| -rw-r--r-- | lib/sqlalchemy/ext/declarative/clsregistry.py | 30 |
4 files changed, 96 insertions, 93 deletions
diff --git a/lib/sqlalchemy/ext/declarative/__init__.py b/lib/sqlalchemy/ext/declarative/__init__.py index eba6cb808..3cbc85c0c 100644 --- a/lib/sqlalchemy/ext/declarative/__init__.py +++ b/lib/sqlalchemy/ext/declarative/__init__.py @@ -955,9 +955,9 @@ Mapping a class using the above mixin, we will get an error like:: sqlalchemy.exc.InvalidRequestError: this ForeignKey's parent column is not yet associated with a Table. -This is because the ``target_id`` :class:`.Column` we've called upon in our ``target()`` -method is not the same :class:`.Column` that declarative is actually going to map -to our table. +This is because the ``target_id`` :class:`.Column` we've called upon in our +``target()`` method is not the same :class:`.Column` that declarative is +actually going to map to our table. The condition above is resolved using a lambda:: @@ -1220,8 +1220,8 @@ assumed to be completed and the 'configure' step has finished:: ``__declare_first__()`` ~~~~~~~~~~~~~~~~~~~~~~~ -Like ``__declare_last__()``, but is called at the beginning of mapper configuration -via the :meth:`.MapperEvents.before_configured` event:: +Like ``__declare_last__()``, but is called at the beginning of mapper +configuration via the :meth:`.MapperEvents.before_configured` event:: class MyClass(Base): @classmethod @@ -1312,6 +1312,6 @@ from .api import declarative_base, synonym_for, comparable_using, \ __all__ = ['declarative_base', 'synonym_for', 'has_inherited_table', - 'comparable_using', 'instrument_declarative', 'declared_attr', - 'ConcreteBase', 'AbstractConcreteBase', 'DeclarativeMeta', - 'DeferredReflection'] + 'comparable_using', 'instrument_declarative', 'declared_attr', + 'ConcreteBase', 'AbstractConcreteBase', 'DeclarativeMeta', + 'DeferredReflection'] diff --git a/lib/sqlalchemy/ext/declarative/api.py b/lib/sqlalchemy/ext/declarative/api.py index 5f3d0742e..daf8bffb5 100644 --- a/lib/sqlalchemy/ext/declarative/api.py +++ b/lib/sqlalchemy/ext/declarative/api.py @@ -9,8 +9,8 @@ from ...schema import Table, MetaData from ...orm import synonym as _orm_synonym, mapper,\ - comparable_property,\ - interfaces, properties + comparable_property,\ + interfaces, properties from ...orm.util import polymorphic_union from ...orm.base import _mapper_or_none from ...util import OrderedDict @@ -18,11 +18,12 @@ from ... import exc import weakref from .base import _as_declarative, \ - _declarative_constructor,\ - _DeferredMapperConfig, _add_attribute + _declarative_constructor,\ + _DeferredMapperConfig, _add_attribute from .clsregistry import _class_resolver from . import clsregistry + def instrument_declarative(cls, registry, metadata): """Given a class, configure the class declaratively, using the given registry, which can be any dictionary, and @@ -31,8 +32,8 @@ def instrument_declarative(cls, registry, metadata): """ if '_decl_class_registry' in cls.__dict__: raise exc.InvalidRequestError( - "Class %r already has been " - "instrumented declaratively" % cls) + "Class %r already has been " + "instrumented declaratively" % cls) cls._decl_class_registry = registry cls.metadata = metadata _as_declarative(cls, cls.__name__, cls.__dict__) @@ -245,6 +246,7 @@ def declarative_base(bind=None, metadata=None, mapper=None, cls=object, return metaclass(name, bases, class_dict) + def as_declarative(**kw): """ Class decorator for :func:`.declarative_base`. @@ -282,6 +284,7 @@ def as_declarative(**kw): return decorate + class ConcreteBase(object): """A helper class for 'concrete' declarative mappings. @@ -323,7 +326,7 @@ class ConcreteBase(object): return polymorphic_union(OrderedDict( (mp.polymorphic_identity, mp.local_table) for mp in mappers - ), 'type', 'pjoin') + ), 'type', 'pjoin') @classmethod def __declare_first__(cls): @@ -478,7 +481,7 @@ class DeferredReflection(object): metadata = mapper.class_.metadata for rel in mapper._props.values(): if isinstance(rel, properties.RelationshipProperty) and \ - rel.secondary is not None: + rel.secondary is not None: if isinstance(rel.secondary, Table): cls._reflect_table(rel.secondary, engine) elif isinstance(rel.secondary, _class_resolver): @@ -506,9 +509,9 @@ class DeferredReflection(object): @classmethod def _reflect_table(cls, table, engine): Table(table.name, - table.metadata, - extend_existing=True, - autoload_replace=False, - autoload=True, - autoload_with=engine, - schema=table.schema) + table.metadata, + extend_existing=True, + autoload_replace=False, + autoload=True, + autoload_with=engine, + schema=table.schema) diff --git a/lib/sqlalchemy/ext/declarative/base.py b/lib/sqlalchemy/ext/declarative/base.py index 41190e407..94baeeb51 100644 --- a/lib/sqlalchemy/ext/declarative/base.py +++ b/lib/sqlalchemy/ext/declarative/base.py @@ -20,6 +20,7 @@ from . import clsregistry import collections import weakref + def _declared_mapping_info(cls): # deferred mapping if _DeferredMapperConfig.has_cls(cls): @@ -59,8 +60,7 @@ def _as_declarative(cls, classname, dict_): cls.__declare_first__() if '__abstract__' in base.__dict__ and base.__abstract__: if (base is cls or - (base in cls.__bases__ and not _is_declarative_inherits) - ): + (base in cls.__bases__ and not _is_declarative_inherits)): return class_mapped = _declared_mapping_info(base) is not None @@ -68,9 +68,9 @@ def _as_declarative(cls, classname, dict_): for name, obj in vars(base).items(): if name == '__mapper_args__': if not mapper_args_fn and ( - not class_mapped or - isinstance(obj, declarative_props) - ): + not class_mapped or + isinstance(obj, declarative_props) + ): # don't even invoke __mapper_args__ until # after we've determined everything about the # mapped table. @@ -80,29 +80,29 @@ def _as_declarative(cls, classname, dict_): mapper_args_fn = lambda: dict(cls.__mapper_args__) elif name == '__tablename__': if not tablename and ( - not class_mapped or - isinstance(obj, declarative_props) - ): + not class_mapped or + isinstance(obj, declarative_props) + ): tablename = cls.__tablename__ elif name == '__table_args__': if not table_args and ( - not class_mapped or - isinstance(obj, declarative_props) - ): + not class_mapped or + isinstance(obj, declarative_props) + ): table_args = cls.__table_args__ if not isinstance(table_args, (tuple, dict, type(None))): raise exc.ArgumentError( - "__table_args__ value must be a tuple, " - "dict, or None") + "__table_args__ value must be a tuple, " + "dict, or None") if base is not cls: inherited_table_args = True elif class_mapped: if isinstance(obj, declarative_props): util.warn("Regular (i.e. not __special__) " - "attribute '%s.%s' uses @declared_attr, " - "but owning class %s is mapped - " - "not applying to subclass %s." - % (base.__name__, name, base, cls)) + "attribute '%s.%s' uses @declared_attr, " + "but owning class %s is mapped - " + "not applying to subclass %s." + % (base.__name__, name, base, cls)) continue elif base is not cls: # we're a mixin. @@ -114,18 +114,18 @@ def _as_declarative(cls, classname, dict_): continue if obj.foreign_keys: raise exc.InvalidRequestError( - "Columns with foreign keys to other columns " - "must be declared as @declared_attr callables " - "on declarative mixin classes. ") + "Columns with foreign keys to other columns " + "must be declared as @declared_attr callables " + "on declarative mixin classes. ") if name not in dict_ and not ( '__table__' in dict_ and (obj.name or name) in dict_['__table__'].c - ) and name not in potential_columns: + ) and name not in potential_columns: potential_columns[name] = \ - column_copies[obj] = \ - obj.copy() + column_copies[obj] = \ + obj.copy() column_copies[obj]._creation_order = \ - obj._creation_order + obj._creation_order elif isinstance(obj, MapperProperty): raise exc.InvalidRequestError( "Mapper properties (i.e. deferred," @@ -134,9 +134,9 @@ def _as_declarative(cls, classname, dict_): "on declarative mixin classes.") elif isinstance(obj, declarative_props): dict_[name] = ret = \ - column_copies[obj] = getattr(cls, name) + column_copies[obj] = getattr(cls, name) if isinstance(ret, (Column, MapperProperty)) and \ - ret.doc is None: + ret.doc is None: ret.doc = obj.__doc__ # apply inherited columns as we should @@ -167,9 +167,8 @@ def _as_declarative(cls, classname, dict_): value = synonym(value.key) setattr(cls, k, value) - if (isinstance(value, tuple) and len(value) == 1 and - isinstance(value[0], (Column, MapperProperty))): + isinstance(value[0], (Column, MapperProperty))): util.warn("Ignoring declarative-like tuple value of attribute " "%s: possibly a copy-and-paste error with a comma " "left at the end of the line?" % k) @@ -198,7 +197,7 @@ def _as_declarative(cls, classname, dict_): if isinstance(c, (ColumnProperty, CompositeProperty)): for col in c.columns: if isinstance(col, Column) and \ - col.table is None: + col.table is None: _undefer_column_name(key, col) if not isinstance(c, CompositeProperty): name_to_prop_key[col.name].add(key) @@ -280,7 +279,7 @@ def _as_declarative(cls, classname, dict_): "Class %r does not have a __table__ or __tablename__ " "specified and does not inherit from an existing " "table-mapped class." % cls - ) + ) elif inherits: inherited_mapper = _declared_mapping_info(inherits) inherited_table = inherited_mapper.local_table @@ -293,14 +292,14 @@ def _as_declarative(cls, classname, dict_): raise exc.ArgumentError( "Can't place __table_args__ on an inherited class " "with no table." - ) + ) # add any columns declared here to the inherited table. for c in declared_columns: if c.primary_key: raise exc.ArgumentError( "Can't place primary key columns on an inherited " "class with no table." - ) + ) if c.name in inherited_table.c: if inherited_table.c[c.name] is c: continue @@ -311,7 +310,7 @@ def _as_declarative(cls, classname, dict_): ) inherited_table.append_column(c) if inherited_mapped_table is not None and \ - inherited_mapped_table is not inherited_table: + inherited_mapped_table is not inherited_table: inherited_mapped_table._refresh_for_new_column(c) defer_map = hasattr(cls, '_sa_decl_prepare') @@ -320,12 +319,12 @@ def _as_declarative(cls, classname, dict_): else: cfg_cls = _MapperConfig mt = cfg_cls(mapper_cls, - cls, table, - inherits, - declared_columns, - column_copies, - our_stuff, - mapper_args_fn) + cls, table, + inherits, + declared_columns, + column_copies, + our_stuff, + mapper_args_fn) if not defer_map: mt.map() @@ -335,12 +334,12 @@ class _MapperConfig(object): mapped_table = None def __init__(self, mapper_cls, - cls, - table, - inherits, - declared_columns, - column_copies, - properties, mapper_args_fn): + cls, + table, + inherits, + declared_columns, + column_copies, + properties, mapper_args_fn): self.mapper_cls = mapper_cls self.cls = cls self.local_table = table @@ -350,7 +349,6 @@ class _MapperConfig(object): self.declared_columns = declared_columns self.column_copies = column_copies - def _prepare_mapper_arguments(self): properties = self.properties if self.mapper_args_fn: @@ -384,7 +382,7 @@ class _MapperConfig(object): set([c.key for c in inherited_table.c if c not in inherited_mapper._columntoproperty]) exclude_properties.difference_update( - [c.key for c in self.declared_columns]) + [c.key for c in self.declared_columns]) # look through columns in the current mapper that # are keyed to a propname different than the colname @@ -413,6 +411,7 @@ class _MapperConfig(object): **mapper_args ) + class _DeferredMapperConfig(_MapperConfig): _configs = util.OrderedDict() @@ -433,32 +432,31 @@ class _DeferredMapperConfig(_MapperConfig): def has_cls(cls, class_): # 2.6 fails on weakref if class_ is an old style class return isinstance(class_, type) and \ - weakref.ref(class_) in cls._configs + weakref.ref(class_) in cls._configs @classmethod def config_for_cls(cls, class_): return cls._configs[weakref.ref(class_)] - @classmethod def classes_for_base(cls, base_cls, sort=True): classes_for_base = [m for m in cls._configs.values() - if issubclass(m.cls, base_cls)] + if issubclass(m.cls, base_cls)] if not sort: return classes_for_base all_m_by_cls = dict( - (m.cls, m) - for m in classes_for_base - ) + (m.cls, m) + for m in classes_for_base + ) tuples = [] for m_cls in all_m_by_cls: tuples.extend( - (all_m_by_cls[base_cls], all_m_by_cls[m_cls]) - for base_cls in m_cls.__bases__ - if base_cls in all_m_by_cls - ) + (all_m_by_cls[base_cls], all_m_by_cls[m_cls]) + for base_cls in m_cls.__bases__ + if base_cls in all_m_by_cls + ) return list( topological.sort( tuples, diff --git a/lib/sqlalchemy/ext/declarative/clsregistry.py b/lib/sqlalchemy/ext/declarative/clsregistry.py index b05c3a647..4595b857a 100644 --- a/lib/sqlalchemy/ext/declarative/clsregistry.py +++ b/lib/sqlalchemy/ext/declarative/clsregistry.py @@ -11,7 +11,7 @@ This system allows specification of classes and expressions used in """ from ...orm.properties import ColumnProperty, RelationshipProperty, \ - SynonymProperty + SynonymProperty from ...schema import _get_table_key from ...orm import class_mapper, interfaces from ... import util @@ -74,7 +74,7 @@ class _MultipleClassMarker(object): def __init__(self, classes, on_remove=None): self.on_remove = on_remove self.contents = set([ - weakref.ref(item, self._remove_item) for item in classes]) + weakref.ref(item, self._remove_item) for item in classes]) _registries.add(self) def __iter__(self): @@ -121,6 +121,7 @@ class _ModuleMarker(object): _decl_class_registry. """ + def __init__(self, name, parent): self.parent = parent self.name = name @@ -161,8 +162,8 @@ class _ModuleMarker(object): existing.add_item(cls) else: existing = self.contents[name] = \ - _MultipleClassMarker([cls], - on_remove=lambda: self._remove_item(name)) + _MultipleClassMarker([cls], + on_remove=lambda: self._remove_item(name)) class _ModNS(object): @@ -182,7 +183,8 @@ class _ModNS(object): assert isinstance(value, _MultipleClassMarker) return value.attempt_get(self.__parent.path, key) raise AttributeError("Module %r has no mapped classes " - "registered under the name %r" % (self.__parent.name, key)) + "registered under the name %r" % ( + self.__parent.name, key)) class _GetColumns(object): @@ -194,8 +196,8 @@ class _GetColumns(object): if mp: if key not in mp.all_orm_descriptors: raise exc.InvalidRequestError( - "Class %r does not have a mapped column named %r" - % (self.cls, key)) + "Class %r does not have a mapped column named %r" + % (self.cls, key)) desc = mp.all_orm_descriptors[key] if desc.extension_type is interfaces.NOT_EXTENSION: @@ -204,13 +206,13 @@ class _GetColumns(object): key = prop.name elif not isinstance(prop, ColumnProperty): raise exc.InvalidRequestError( - "Property %r is not an instance of" - " ColumnProperty (i.e. does not correspond" - " directly to a Column)." % key) + "Property %r is not an instance of" + " ColumnProperty (i.e. does not correspond" + " directly to a Column)." % key) return getattr(self.cls, key) inspection._inspects(_GetColumns)( - lambda target: inspection.inspect(target.cls)) + lambda target: inspection.inspect(target.cls)) class _GetTable(object): @@ -220,8 +222,8 @@ class _GetTable(object): def __getattr__(self, key): return self.metadata.tables[ - _get_table_key(key, self.key) - ] + _get_table_key(key, self.key) + ] def _determine_container(key, value): @@ -248,7 +250,7 @@ class _class_resolver(object): elif key in cls.metadata._schemas: return _GetTable(key, cls.metadata) elif '_sa_module_registry' in cls._decl_class_registry and \ - key in cls._decl_class_registry['_sa_module_registry']: + key in cls._decl_class_registry['_sa_module_registry']: registry = cls._decl_class_registry['_sa_module_registry'] return registry.resolve_attr(key) elif self._resolvers: |
