signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def _read_widget(self):
getter = self._wid_info[self._wid][<NUM_LIT:0>]<EOL>return getter(self._wid)<EOL>
Returns the value currently stored into the widget, after transforming it accordingly to possibly specified function. This is implemented by calling the getter provided by the user. This method can raise InvalidValue (raised by the getter) when the value in the widget must not be considered as valid.
f2888:c1:m12
def _write_widget(self, val):
self._itsme = True<EOL>try:<EOL><INDENT>setter = self._wid_info[self._wid][<NUM_LIT:1>]<EOL>wtype = self._wid_info[self._wid][<NUM_LIT:2>]<EOL>if setter:<EOL><INDENT>if wtype is not None:<EOL><INDENT>setter(self._wid, self._cast_value(val, wtype))<EOL><DEDENT>else:<EOL><INDENT>setter(self._wid, val)<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>self._itsme = False<EOL><DEDENT>
Writes value into the widget. If specified, user setter is invoked.
f2888:c1:m13
def _on_wid_changed(self, wid, *args):
if self._itsme:<EOL><INDENT>return<EOL><DEDENT>self.update_model()<EOL>
Called when the widget is changed
f2888:c1:m15
def _on_prop_changed(self):
if self._wid and not self._itsme:<EOL><INDENT>self.update_widget()<EOL><DEDENT>
Called by the observation code, when the value in the observed property is changed
f2888:c1:m16
def _resolve_to_func(self, what):
if isinstance(what, str):<EOL><INDENT>what = getattr(Adapter._get_property(self), what)<EOL><DEDENT>if type(what) == types.MethodType:<EOL><INDENT>what = what.__func__<EOL><DEDENT>if not type(what) == types.FunctionType:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return what<EOL>
This method resolves whatever is passed: a string, a bound or unbound method, a function, to make it a function. This makes internal handling of setter and getter uniform and easier.
f2888:c2:m1
def _on_prop_changed(self, instance, meth_name, res, args, kwargs):
Adapter._on_prop_changed(self)<EOL>
Called by the observation code, when a modifying method is called
f2888:c2:m3
def _get_property(self, *args):
val = self._getter(Adapter._get_property(self), *args)<EOL>if self._prop_read:<EOL><INDENT>return self._prop_read(val, *args)<EOL><DEDENT>return val<EOL>
Private method that returns the value currently stored into the property
f2888:c2:m4
def _set_property(self, val, *args):
if self._prop_write:<EOL><INDENT>val = self._prop_write(val)<EOL><DEDENT>return self._setter(Adapter._get_property(self), val, *args)<EOL>
Private method that sets the value currently of the property
f2888:c2:m5
def _get_observer_fun(self, prop_name):
return Adapter._get_observer_fun(self, prop_name)<EOL>
Restore Adapter's behaviour to make possible to receive value change notifications
f2888:c3:m1
def _on_prop_changed(self):
return Adapter._on_prop_changed(self)<EOL>
Again to restore behaviour of Adapter
f2888:c3:m2
def _set_property(self, val, *args):
val = UserClassAdapter._set_property(self, val, *args)<EOL>if val:<EOL><INDENT>Adapter._set_property(self, val, *args)<EOL><DEDENT>return val<EOL>
Private method that sets the value currently of the property
f2888:c3:m3
def connect_widget(self, wid, getters=None, setters=None,<EOL>signals=None, arg=None,<EOL>flavours=None):
if isinstance(wid, Gtk.Container):<EOL><INDENT>self._widgets = wid.get_children()<EOL><DEDENT>elif isinstance(wid, (list, tuple)):<EOL><INDENT>self._widgets = wid<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>for idx, w in enumerate(self._widgets):<EOL><INDENT>if self._prop_is_map: idx=_get_name(w)<EOL>self._idx2wid[idx] = w<EOL>self._wid2idx[w] = idx<EOL>pass<EOL><DEDENT>getters = self.__handle_par("<STR_LIT>", getters)<EOL>setters = self.__handle_par("<STR_LIT>", setters)<EOL>signals = self.__handle_par("<STR_LIT>", signals)<EOL>flavours = self.__handle_par("<STR_LIT>", flavours)<EOL>for wi,ge,se,si,fl in zip(self._widgets, getters, setters, signals, flavours):<EOL><INDENT>if type(ge) == types.MethodType: ge = ge.im_func<EOL>if type(se) == types.MethodType: se = se.im_func<EOL>UserClassAdapter.connect_widget(self, wi, ge, se, si, arg, False, fl)<EOL>pass<EOL><DEDENT>self.update_widget()<EOL>self._wid = wid<EOL>return<EOL>
Called when the widget is instantiated, and the adapter is ready to connect the widgets inside it (if a container) or each widget if wid is a list of widgets. getters and setters can be None, a function or a list or a map of functions. signals can be None, a signal name, or a list or a map of signal names. When maps are used, keys can be widgets or widget names. The length of the possible lists or maps must be lesser or equal to the number of widgets that will be connected.
f2890:c0:m1
def update_model(self, idx=None):
if idx is None:<EOL><INDENT>for w in self._widgets:<EOL><INDENT>idx = self._get_idx_from_widget(w)<EOL>try: val = self._read_widget(idx)<EOL>except ValueError: pass<EOL>else: self._write_property(val, idx)<EOL>pass<EOL><DEDENT>pass<EOL><DEDENT>else:<EOL><INDENT>try: val = self._read_widget(idx)<EOL>except ValueError: pass<EOL>else: self._write_property(val, idx)<EOL><DEDENT>return<EOL>
Updates the value of property at given index. If idx is None, all controlled indices will be updated. This method should be called directly by the user in very unusual conditions.
f2890:c0:m2
def update_widget(self, idx=None):
if idx is None:<EOL><INDENT>for w in self._widgets:<EOL><INDENT>idx = self._get_idx_from_widget(w)<EOL>self._write_widget(self._read_property(idx), idx)<EOL><DEDENT>pass<EOL><DEDENT>else: self._write_widget(self._read_property(idx), idx)<EOL>return<EOL>
Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual conditions.
f2890:c0:m3
def _get_idx_from_widget(self, wid):
return self._wid2idx[wid]<EOL>
Given a widget, returns the corresponding index for the model. Returned value can be either an integer or a string
f2890:c0:m4
def _get_widget_from_idx(self, idx):
return self._idx2wid[idx]<EOL>
Given an index, returns the corresponding widget for the view. Given index can be either an integer or a string
f2890:c0:m5
def _on_wid_changed(self, wid):
if self._itsme: return<EOL>self.update_model(self._get_idx_from_widget(wid))<EOL>return<EOL>
Called when the widget is changed
f2890:c0:m9
def _on_prop_changed(self, instance, meth_name, res, args, kwargs):
if not self._itsme and meth_name == "<STR_LIT>": self.update_widget(args[<NUM_LIT:0>])<EOL>return<EOL>
Called by the observation code, we are interested in __setitem__
f2890:c0:m10
def __init__(self, tree, column=<NUM_LIT:0>):
Observer.__init__(self)<EOL>self.column = column<EOL>self.rows = weakref.WeakKeyDictionary()<EOL>tree.foreach(self.on_changed)<EOL>tree.connect('<STR_LIT>', self.on_changed)<EOL>
Observe models stored in a list for assignment to their observable properties, and notify the container that the row has changed. *tree* is a :class:`Gtk.TreeModel` instance. *column* is an integer adressing the column of *tree* that contains :class:`gtkmvc3.Model` instances.
f2890:c1:m0
@decorators.good_decorator_accepting_args<EOL>def observes(*args):
@decorators.good_decorator<EOL>def _decorator(_notified):<EOL><INDENT>_list = getattr(_notified, Observer._CUST_OBS_, list())<EOL>margs, mvarargs, _, _ = inspect.getargspec(_notified)<EOL>mnumargs = len(margs)<EOL>if not mvarargs:<EOL><INDENT>args_to_type = {<NUM_LIT:4>: '<STR_LIT>',<EOL><NUM_LIT:5>: '<STR_LIT>',<EOL><NUM_LIT:7>: '<STR_LIT>',<EOL><NUM_LIT:8>: '<STR_LIT>',<EOL>}<EOL>try :<EOL><INDENT>type_kw = args_to_type[mnumargs]<EOL>_list += [(arg, dict({type_kw : True,<EOL>'<STR_LIT>' : True}))<EOL>for arg in args]<EOL>setattr(_notified, Observer._CUST_OBS_, _list)<EOL><DEDENT>except KeyError:<EOL><INDENT>log.logger.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>_notified.__name__, mnumargs,<EOL>"<STR_LIT:U+002C>".join(map(str, args_to_type)))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.logger.warn("<STR_LIT>"<EOL>"<STR_LIT>", _notified.__name__)<EOL><DEDENT>return _notified<EOL><DEDENT>if <NUM_LIT:0> == len(args):<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if any(a for a in args if not isinstance(a, str)):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>log.logger.warning("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return _decorator<EOL>
Decorate a method in an :class:`Observer` subclass as a notification. Takes one to many property names as strings. If any of them changes in a model we observe, the method is called. The name of the property will be passed to the method. The type of notification is inferred from the number of arguments. Valid signature are:: def value_notify(self, model, name, old, new) def before_notify(self, model, name, instance, method_name, args, kwargs) def after_notify(self, model, name, instance, method_name, res, args, kwargs) def signal_notify(self, model, name, arg) .. versionadded:: 1.99.0 .. deprecated:: 1.99.1 Use :meth:`Observer.observe` instead, which offers more features.
f2891:m0
def __getattr__(self, name):
try:<EOL><INDENT>return self[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise AttributeError("<STR_LIT>"<EOL>"<STR_LIT>" %(name, str(self)))<EOL><DEDENT>
All dictionary keys are also available as attributes.
f2891:c0:m1
@classmethod<EOL><INDENT>@decorators.good_decorator_accepting_args<EOL>def observe(cls, *args, **kwargs):<DEDENT>
@decorators.good_decorator<EOL>def _decorator(_notified):<EOL><INDENT>_list = getattr(_notified, Observer._CUST_OBS_, list())<EOL>_list.append((name, kwargs))<EOL>setattr(_notified, Observer._CUST_OBS_, _list)<EOL>return _notified<EOL><DEDENT>if args and isinstance(args[<NUM_LIT:0>], cls):<EOL><INDENT>if len(args) != <NUM_LIT:3>:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>" % len(args))<EOL><DEDENT>self = args[<NUM_LIT:0>]<EOL>notified = args[<NUM_LIT:1>]<EOL>name = args[<NUM_LIT:2>]<EOL>assert isinstance(self, Observer), "<STR_LIT>""<STR_LIT>"<EOL>if not callable(notified):<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if not isinstance(name, str):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.__register_notification(name, notified, kwargs)<EOL>return None<EOL><DEDENT>if len(args) != <NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>" % len(args))<EOL><DEDENT>name = args[<NUM_LIT:0>]<EOL>if not isinstance(name, str):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return _decorator<EOL>
Mark a method as receiving notifications. Comes in two flavours: .. method:: observe(name, **types) :noindex: A decorator living in the class. Can be applied more than once to the same method, provided the names differ. *name* is the property we want to be notified about as a string. .. Note:: Alternatively, *name* can be a pattern for matching property names, meaning it can contain wildcards character like in module `fnmatch <http://docs.python.org/library/fnmatch.html>`_ in Python library. However, if wildcards are used in name, only *one* `observe` can be used for a given notification method, or else `ValueError` exception is raised when the Observer class is instantiated. .. versionadded:: 1.99.2 *types* are boolean values denoting the types of notifications desired. At least one of the following has to be passed as True: assign, before, after, signal. Excess keyword arguments are passed to the method as part of the info dictionary. .. method:: observe(callable, name, **types) :noindex: An instance method to define notifications at runtime. Works as above. *callable* is the method to send notifications to. The effect will be as if this had been decorated. In all cases the notification method must take exactly three arguments: the model object, the name of the property that changed, and an :class:`NTInfo` object describing the change. .. warning:: Due to limitation in the dynamic registration (in version 1.99.1), declarations of dynamic notifications must occur before registering self as an observer of the models whose properties the notifications are supposed to be observing. A hack for this limitation, is to first relieve any interesting model before dynamically register the notifications, and then re-observe those models. .. versionadded:: 1.99.1
f2891:c1:m0
def __init__(self, model=None, spurious=False):
<EOL>def __observe(*args, **kwargs):<EOL><INDENT>self.__original_observe(self, *args, **kwargs)<EOL><DEDENT>__observe.__name__ = self.observe.__name__<EOL>__observe.__doc__ = self.observe.__doc__<EOL>self.__original_observe = self.observe<EOL>self.observe = __observe<EOL>self.__accepts_spurious__ = spurious<EOL>self.__PROP_TO_METHS = {} <EOL>self.__METH_TO_PROPS = {} <EOL>self.__PAT_TO_METHS = {}<EOL>self.__METH_TO_PAT = {} <EOL>self.__PAT_METH_TO_KWARGS = {} <EOL>processed_props = set() <EOL>for cls in inspect.getmro(type(self)):<EOL><INDENT>meths = [(name, meth, getattr(meth, Observer._CUST_OBS_))<EOL>for name, meth in cls.__dict__.items()<EOL>if (inspect.isfunction(meth) and<EOL>hasattr(meth, Observer._CUST_OBS_))]<EOL>cls_processed_props = set()<EOL>for name, meth, pnames_ka in meths:<EOL><INDENT>_method = getattr(self, name) <EOL>for pname, ka in pnames_ka:<EOL><INDENT>if pname not in processed_props:<EOL><INDENT>self.__register_notification(pname, _method, ka)<EOL>cls_processed_props.add(pname)<EOL><DEDENT><DEDENT><DEDENT>processed_props |= cls_processed_props<EOL><DEDENT>if model:<EOL><INDENT>self.observe_model(model)<EOL><DEDENT>
*model* is passed to :meth:`observe_model` if given. *spurious* indicates interest to be notified even when the value hasn't changed, like for: :: model.prop = model.prop .. versionadded:: 1.2.0 Before that observers had to filter out spurious notifications themselves, as if the default was `True`. With :class:`~gtkmvc3.observable.Signal` support this is no longer necessary.
f2891:c1:m1
def observe_model(self, model):
return model.register_observer(self)<EOL>
Starts observing the given model
f2891:c1:m2
def relieve_model(self, model):
return model.unregister_observer(self)<EOL>
Stops observing the given model
f2891:c1:m3
def accepts_spurious_change(self):
return self.__accepts_spurious__<EOL>
Returns True if this observer is interested in receiving spurious value changes. This is queried by the model when notifying a value change.
f2891:c1:m4
def get_observing_methods(self, prop_name):
<EOL>return (functools.reduce(set.union,<EOL>(meths<EOL>for pat, meths in self.__PAT_TO_METHS.items()<EOL>if fnmatch.fnmatch(prop_name, pat)),<EOL>set()) |<EOL>self.__PROP_TO_METHS.get(prop_name, set()))<EOL>
Return a possibly empty set of callables registered with :meth:`observe` for *prop_name*. The returned set includes those notifications which have been registered by means of patterns matching prop_name. .. versionadded:: 1.99.1 Replaces :meth:`get_custom_observing_methods`.
f2891:c1:m5
def get_observing_method_kwargs(self, prop_name, method):
<EOL>if (prop_name, method) in self.__PAT_METH_TO_KWARGS:<EOL><INDENT>return self.__PAT_METH_TO_KWARGS[(prop_name, method)]<EOL><DEDENT>if method in self.__METH_TO_PAT:<EOL><INDENT>prop_name = self.__METH_TO_PAT[method]<EOL><DEDENT>return self.__PAT_METH_TO_KWARGS[(prop_name, method)]<EOL>
Returns the keyword arguments which were specified when declaring a notification method, either statically or dynamically with :meth:`Observer.observe`. Since patterns may be involved when declaring the notifications, first exact match is checked, and then the single-allowed pattern is checked, if there is any. *method* a callable that was registered with :meth:`observe`. :rtype: dict
f2891:c1:m6
def remove_observing_method(self, prop_names, method):
for prop_name in prop_names:<EOL><INDENT>if prop_name in self.__PROP_TO_METHS:<EOL><INDENT>self.__PROP_TO_METHS[prop_name].remove(method)<EOL>del self.__PAT_METH_TO_KWARGS[(prop_name, method)]<EOL><DEDENT>elif method in self.__METH_TO_PAT:<EOL><INDENT>pat = self.__METH_TO_PAT[method]<EOL>if fnmatch.fnmatch(prop_name, pat):<EOL><INDENT>del self.__METH_TO_PAT[method]<EOL>self.__PAT_TO_METHS[pat].remove(method)<EOL><DEDENT>del self.__PAT_METH_TO_KWARGS[(pat, method)]<EOL><DEDENT><DEDENT>
Remove dynamic notifications. *method* a callable that was registered with :meth:`observe`. *prop_names* a sequence of strings. This need not correspond to any one `observe` call. .. note:: This can revert even the effects of decorator `observe` at runtime. Don't.
f2891:c1:m7
def is_observing_method(self, prop_name, method):
if (prop_name, method) in self.__PAT_METH_TO_KWARGS:<EOL><INDENT>return True<EOL><DEDENT>if method in self.__METH_TO_PAT:<EOL><INDENT>pat = self.__METH_TO_PAT[method]<EOL>if fnmatch.fnmatch(prop_name, pat):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
Returns `True` if the given method was previously added as an observing method, either dynamically or via decorator.
f2891:c1:m8
def __register_notification(self, prop_name, method, kwargs):
key = (prop_name, method)<EOL>if key in self.__PAT_METH_TO_KWARGS:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %(self.__class__,<EOL>method.__name__, prop_name))<EOL><DEDENT>if frozenset(prop_name) & WILDCARDS:<EOL><INDENT>if (method in self.__METH_TO_PAT or<EOL>(method in self.__METH_TO_PROPS and<EOL>self.__METH_TO_PROPS[method])):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %(self.__class__, method.__name__))<EOL><DEDENT>self.__METH_TO_PAT[method] = prop_name<EOL>_dict = self.__PAT_TO_METHS<EOL><DEDENT>else:<EOL><INDENT>if method in self.__METH_TO_PAT:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %(self.__class__, method.__name__))<EOL><DEDENT>_dict = self.__PROP_TO_METHS<EOL>if method not in self.__METH_TO_PROPS:<EOL><INDENT>self.__METH_TO_PROPS[method] = set()<EOL><DEDENT>self.__METH_TO_PROPS[method].add(prop_name)<EOL><DEDENT>if prop_name not in _dict:<EOL><INDENT>_dict[prop_name] = set()<EOL><DEDENT>_dict[prop_name].add(method)<EOL>self.__PAT_METH_TO_KWARGS[key] = kwargs<EOL>
Internal service which associates the given property name to the method, and the (prop_name, method) with the given kwargs dictionary. If needed merges the dictionary, if the given (prop_name, method) pair was already registered (in this case the last registration wins in case of overlapping.) If given prop_name and method have been already registered, a ValueError exception is raised.
f2891:c1:m9
def get_version():
return __version<EOL>
Return the imported version of this framework as a tuple of integers.
f2892:m0
def require(request):
try:<EOL><INDENT>request = request.split("<STR_LIT:.>")<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>request = [int(x) for x in request]<EOL>provide = list(__version)<EOL>if request > provide:<EOL><INDENT>raise AssertionError("<STR_LIT>" % (<EOL>request, provide))<EOL><DEDENT>
Raise :exc:`AssertionError` if gtkmvc3 version is not compatible. *request* a dotted string or iterable of string or integers representing the minimum version you need. :: require("1.0") require(("1", "2", "2")) require([1,99,0]) .. note:: For historical reasons this does not take all API changes into account. Some are caught by the argument checks in View and Controller constructors.
f2892:m1
def __add_model__(self, model, prop_name):
self.__models.add((model, prop_name))<EOL>
Registers the given model to hold the wrapper among its properties, within a property whose name is given as well
f2894:c0:m1
def __remove_model__(self, model, prop_name):
self.__models.remove((model, prop_name))<EOL>
Unregisters the given model, to release the wrapper. This method reverts the effect of __add_model__
f2894:c0:m2
@staticmethod<EOL><INDENT>def __fix_bases(base_classes, have_mt):<DEDENT>
fixed = list(base_classes)<EOL>contains_model = False<EOL>for b in fixed:<EOL><INDENT>if isinstance(fixed, Model): contains_model = True; break<EOL>pass<EOL><DEDENT>if not contains_model:<EOL><INDENT>if have_mt:<EOL><INDENT>from gtkmvc3.model_mt import ModelMT<EOL>fixed.insert(<NUM_LIT:0>, ModelMT)<EOL><DEDENT>else: fixed.insert(<NUM_LIT:0>, Model)<EOL>pass<EOL><DEDENT>class ModelFactoryWrap (object, metaclass=get_noconflict_metaclass(tuple(fixed), (), ())):<EOL><INDENT>def __init__(self, *args, **kwargs): pass<EOL>pass<EOL><DEDENT>fixed.append(ModelFactoryWrap)<EOL>fixed.sort()<EOL>return tuple(fixed)<EOL>
This function check whether base_classes contains a Model instance. If not, choose the best fitting class for model. Furthermore, it makes the list in a cannonical ordering form in a way that ic can be used as memoization key
f2895:c0:m0
@staticmethod<EOL><INDENT>def make(base_classes=(), have_mt=False):<DEDENT>
good_bc = ModelFactory.__fix_bases(base_classes, have_mt)<EOL>print("<STR_LIT>", good_bc)<EOL>key = "<STR_LIT>".join(map(str, good_bc))<EOL>if key in ModelFactory.__memoized:<EOL><INDENT>return ModelFactory.__memoized[key]<EOL><DEDENT>cls = new.classobj('<STR_LIT>', good_bc, {'<STR_LIT>': '<STR_LIT:__main__>', '<STR_LIT>': None})<EOL>ModelFactory.__memoized[key] = cls<EOL>return cls<EOL>
Use this static method to build a model class that possibly derives from other classes. If have_mt is True, then returned class will take into account multi-threading issues when dealing with observable properties.
f2895:c0:m1
def skip_redundant(iterable, skipset=None):
if skipset is None: skipset = set()<EOL>for item in iterable:<EOL><INDENT>if item not in skipset:<EOL><INDENT>skipset.add(item)<EOL>yield item<EOL><DEDENT><DEDENT>
Redundant items are repeated items or items in the original skipset.
f2898:m0
def get_noconflict_metaclass(bases, left_metas, right_metas):
<EOL>metas = left_metas + tuple(map(type, bases)) + right_metas<EOL>needed_metas = remove_redundant(metas)<EOL>if needed_metas in memoized_metaclasses_map:<EOL><INDENT>return memoized_metaclasses_map[needed_metas]<EOL><DEDENT>elif not needed_metas: <EOL><INDENT>meta = type<EOL><DEDENT>elif len(needed_metas) == <NUM_LIT:1>: <EOL><INDENT>meta = needed_metas[<NUM_LIT:0>]<EOL><DEDENT>elif needed_metas == bases: <EOL><INDENT>raise TypeError("<STR_LIT>", needed_metas)<EOL><DEDENT>else: <EOL><INDENT>metaname = '<STR_LIT:_>' + '<STR_LIT>'.join([m.__name__ for m in needed_metas])<EOL>meta = classmaker()(metaname, needed_metas, {})<EOL><DEDENT>memoized_metaclasses_map[needed_metas] = meta<EOL>return meta<EOL>
Not intended to be used outside of this module, unless you know what you are doing.
f2898:m2
def __init__(cls, name, bases, _dict):
type.__init__(cls, name, bases, _dict)<EOL>obs = set()<EOL>conc_props, log_props = type(cls).__get_observables_sets__(cls)<EOL>for prop in conc_props:<EOL><INDENT>val = _dict[prop] <EOL>type(cls).__create_conc_prop_accessors__(cls, prop, val)<EOL>obs.add(prop)<EOL><DEDENT>_getdict = getattr(cls, LOGICAL_GETTERS_MAP_NAME, dict())<EOL>_setdict = getattr(cls, LOGICAL_SETTERS_MAP_NAME, dict())<EOL>real_log_props = type(cls).__create_log_props(cls, log_props,<EOL>_getdict, _setdict)<EOL>obs |= real_log_props<EOL>_getdict.clear()<EOL>_setdict.clear()<EOL>props = getattr(cls, PROPS_MAP_NAME, {})<EOL>if len(props) > <NUM_LIT:0>:<EOL><INDENT>import warnings<EOL>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"% (cls.__module__, cls.__name__,<EOL>PROPS_MAP_NAME, OBS_TUPLE_NAME),<EOL>DeprecationWarning)<EOL><DEDENT>for prop in (x for x in props if x not in obs):<EOL><INDENT>type(cls).__create_conc_prop_accessors__(cls, prop, props[prop])<EOL>obs.add(prop)<EOL><DEDENT>for base in bases: obs |= getattr(base, ALL_OBS_SET, set())<EOL>setattr(cls, ALL_OBS_SET, frozenset(obs))<EOL>logger.debug("<STR_LIT>"% (cls.__module__, cls.__name__, obs))<EOL>return<EOL>
class constructor
f2899:c0:m0
def __get_observables_sets__(cls):
conc_prop_set = set()<EOL>log_prop_set = set()<EOL>not_found = []<EOL>names = cls.__dict__.get(OBS_TUPLE_NAME, tuple())<EOL>if not isinstance(names, list) andnot isinstance(names, tuple):<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>" %(cls.__module__, cls.__name__, OBS_TUPLE_NAME))<EOL><DEDENT>for name in names:<EOL><INDENT>if not isinstance(name, str):<EOL><INDENT>raise TypeError("<STR_LIT>""<STR_LIT>" %<EOL>(cls.__module__, cls.__name__, OBS_TUPLE_NAME,<EOL>type(name)))<EOL><DEDENT>if (name in cls.__dict__ and<EOL>not isinstance(getattr(cls, name), (types.MethodType, types.FunctionType))):<EOL><INDENT>conc_prop_set.add(name)<EOL><DEDENT>else:<EOL><INDENT>not_found.append(name)<EOL><DEDENT><DEDENT>concrete_members = [x for x, v in cls.__dict__.items()<EOL>if (not x.startswith("<STR_LIT>") and<EOL>not isinstance(v, types.FunctionType) and<EOL>not isinstance(v, types.MethodType) and<EOL>not isinstance(v, classmethod) and<EOL>x not in conc_prop_set)]<EOL>for pat in not_found:<EOL><INDENT>if frozenset(pat) & WILDCARDS:<EOL><INDENT>matches = fnmatch.filter(concrete_members, pat)<EOL>if <NUM_LIT:0> == len(matches):<EOL><INDENT>logger.warning("<STR_LIT>""<STR_LIT>",<EOL>cls.__module__, cls.__name__, pat)<EOL><DEDENT>else: conc_prop_set |= set(matches)<EOL><DEDENT>else: <EOL><INDENT>log_prop_set.add(pat)<EOL><DEDENT><DEDENT>return (frozenset(conc_prop_set), frozenset(log_prop_set))<EOL>
Returns a pair of frozensets. First set of strings is the set of concrete properties, obtained by expanding wildcards found in class field __observables__. Expansion works only with names not prefixed with __. Second set of strings contains the names of the logical properties. This set may still contain logical properties which have not been associated with a getter (and optionally with a setter).
f2899:c0:m1
def __create_log_props(cls, log_props, _getdict, _setdict):
real_log_props = set()<EOL>resolved_getdict = {}<EOL>resolved_setdict = {}<EOL>for _dict_name, _dict, _resolved_dict in (<EOL>("<STR_LIT>", _getdict, resolved_getdict),<EOL>("<STR_LIT>", _setdict, resolved_setdict)):<EOL><INDENT>for pat, ai in ((pat, ai)<EOL>for pat, ai in _dict.items()<EOL>if frozenset(pat) & WILDCARDS):<EOL><INDENT>matches = fnmatch.filter(log_props, pat)<EOL>for match in matches:<EOL><INDENT>if match in _resolved_dict:<EOL><INDENT>raise NameError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %(cls.__module__, cls.__name__, _dict_name, match))<EOL><DEDENT>_resolved_dict[match] = ai<EOL><DEDENT>if not matches:<EOL><INDENT>logger.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>cls.__module__, cls.__name__, _dict_name, pat)<EOL><DEDENT><DEDENT>_resolved_dict.update((name, ai)<EOL>for name, ai in _dict.items()<EOL>if name in log_props)<EOL>not_found = [name for name in _resolved_dict<EOL>if name not in log_props]<EOL>if not_found:<EOL><INDENT>logger.warning("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>cls.__module__, cls.__name__, _dict_name,<EOL>str(not_found))<EOL><DEDENT><DEDENT>for name in log_props:<EOL><INDENT>ai_get = resolved_getdict.get(name, None)<EOL>if ai_get:<EOL><INDENT>_getter = type(cls).get_getter(cls, name, ai_get.func,<EOL>ai_get.has_args)<EOL>_deps = ai_get.deps<EOL><DEDENT>else:<EOL><INDENT>_getter = type(cls).get_getter(cls, name)<EOL>if _getter is None:<EOL><INDENT>raise RuntimeError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %(cls.__module__, cls.__name__, name))<EOL><DEDENT>_deps = type(cls)._get_old_style_getter_deps(cls, name,<EOL>_getter)<EOL><DEDENT>ai_set = resolved_setdict.get(name, None)<EOL>if ai_set:<EOL><INDENT>if ai_get:<EOL><INDENT>_setter = type(cls).get_setter(cls, name,<EOL>ai_set.func, ai_set.has_args,<EOL>ai_get.func, ai_get.has_args)<EOL><DEDENT>else:<EOL><INDENT>_setter = type(cls).get_setter(cls, name,<EOL>ai_set.func, ai_set.has_args,<EOL>_getter, False)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if ai_get:<EOL><INDENT>_setter = type(cls).get_setter(cls, name,<EOL>None, None,<EOL>ai_get.func,<EOL>ai_get.has_args)<EOL><DEDENT>else:<EOL><INDENT>_setter = type(cls).get_setter(cls, name)<EOL><DEDENT><DEDENT>prop = PropertyMeta.LogicalOP(_getter, _setter, frozenset(_deps))<EOL>setattr(cls, name, prop)<EOL>real_log_props.add(name)<EOL><DEDENT>setters_no_getters = (set(resolved_setdict) - real_log_props) &log_props<EOL>if setters_no_getters:<EOL><INDENT>logger.warning("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>cls.__module__, cls.__name__,<EOL>"<STR_LIT:U+002CU+0020>".join(setters_no_getters))<EOL><DEDENT>return frozenset(real_log_props)<EOL>
Creates all the logical property. The list of names of properties to be created is passed with frozenset log_props. The getter/setter information is taken from _{get,set}dict. This method resolves also wildcards in names, and performs all checks to ensure correctness. Returns the frozen set of the actually created properties (as not log_props may be really created, e.g. when no getter is provided, and a warning is issued).
f2899:c0:m2
def _get_old_style_getter_deps(cls, prop_name, _getter):
args, _, _, defaults = inspect.getargspec(_getter)<EOL>try:<EOL><INDENT>idx = args.index(KWARG_NAME_DEPS) - (len(args) - len(defaults))<EOL>if idx < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %(cls.__module__, cls.__name__,<EOL>_getter.__name__, KWARG_NAME_DEPS))<EOL><DEDENT>_deps = defaults[idx]<EOL>if not hasattr(_deps, '<STR_LIT>'):<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %(cls.__module__, cls.__name__,<EOL>_getter.__name__, KWARG_NAME_DEPS))<EOL><DEDENT>for dep in _deps:<EOL><INDENT>if not isinstance(dep, str):<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %(cls.__module__, cls.__name__,<EOL>_getter.__name__,<EOL>KWARG_NAME_DEPS))<EOL><DEDENT><DEDENT><DEDENT>except ValueError:<EOL><INDENT>_deps = ()<EOL><DEDENT>return _deps<EOL>
Checks if deps were given with argument 'deps' (only for old-style getters (not based on decorator). Checks types, and returns the value (iterable of strings) given with the argument 'deps
f2899:c0:m3
def __create_conc_prop_accessors__(cls, prop_name, default_val):
getter_name = "<STR_LIT>" % prop_name<EOL>setter_name = "<STR_LIT>" % prop_name<EOL>members_names = frozenset(cls.__dict__.keys())<EOL>if getter_name not in members_names:<EOL><INDENT>_getter = type(cls).get_getter(cls, prop_name)<EOL>setattr(cls, getter_name, _getter)<EOL><DEDENT>else:<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>"<STR_LIT>", getter_name, prop_name)<EOL><DEDENT>if setter_name not in members_names:<EOL><INDENT>_setter = type(cls).get_setter(cls, prop_name)<EOL>setattr(cls, setter_name, _setter)<EOL><DEDENT>else:<EOL><INDENT>logger.warning("<STR_LIT>"<EOL>"<STR_LIT>", setter_name, prop_name)<EOL><DEDENT>prop = PropertyMeta.ConcreteOP(getattr(cls, getter_name),<EOL>getattr(cls, setter_name))<EOL>setattr(cls, prop_name, prop)<EOL>varname = PROP_NAME % {'<STR_LIT>' : prop_name}<EOL>if varname not in members_names:<EOL><INDENT>setattr(cls, varname, cls.create_value(varname, default_val))<EOL><DEDENT>else:<EOL><INDENT>logger.warning("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>cls.__module__, cls.__name__, varname)<EOL><DEDENT>
Private method that creates getter and setter, and the corresponding property. This is used for concrete properties.
f2899:c0:m4
def has_prop_attribute(cls, prop_name):
return (prop_name in cls.__dict__ and<EOL>not isinstance(cls.__dict__[prop_name], types.FunctionType))<EOL>
This methods returns True if there exists a class attribute for the given property. The attribute is searched locally only
f2899:c0:m5
def check_value_change(cls, old, new):
return (type(old) != type(new) or<EOL>isinstance(old, wrappers.ObsWrapperBase) and old != new)<EOL>
Checks whether the value of the property changed in type or if the instance has been changed to a different instance. If true, a call to model._reset_property_notification should be called in order to re-register the new property instance or type
f2899:c0:m6
def create_value(cls, prop_name, val, model=None):
if isinstance(val, tuple):<EOL><INDENT>if len(val) == <NUM_LIT:3>:<EOL><INDENT>try:<EOL><INDENT>wrap_instance = isinstance(val[<NUM_LIT:1>], val[<NUM_LIT:0>]) and(isinstance(val[<NUM_LIT:2>], tuple) or<EOL>isinstance(val[<NUM_LIT:2>], list))<EOL><DEDENT>except TypeError:<EOL><INDENT>pass <EOL><DEDENT>else:<EOL><INDENT>if wrap_instance:<EOL><INDENT>res = wrappers.ObsUserClassWrapper(val[<NUM_LIT:1>], val[<NUM_LIT:2>])<EOL>if model:<EOL><INDENT>res.__add_model__(model, prop_name)<EOL><DEDENT>return res<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif isinstance(val, list):<EOL><INDENT>res = wrappers.ObsListWrapper(val)<EOL>if model:<EOL><INDENT>res.__add_model__(model, prop_name)<EOL><DEDENT>return res<EOL><DEDENT>elif isinstance(val, set):<EOL><INDENT>res = wrappers.ObsSetWrapper(val)<EOL>if model:<EOL><INDENT>res.__add_model__(model, prop_name)<EOL><DEDENT>return res<EOL><DEDENT>elif isinstance(val, dict):<EOL><INDENT>res = wrappers.ObsMapWrapper(val)<EOL>if model:<EOL><INDENT>res.__add_model__(model, prop_name)<EOL><DEDENT>return res<EOL><DEDENT>return val<EOL>
This is used to create a value to be assigned to a property. Depending on the type of the value, different values are created and returned. For example, for a list, a ListWrapper is created to wrap it, and returned for the assignment. model is different from None when the value is changed (a model exists). Otherwise, during property creation model is None
f2899:c0:m7
def get_getter(cls, prop_name, <EOL>user_getter=None, getter_takes_name=False):
if user_getter:<EOL><INDENT>if getter_takes_name: <EOL><INDENT>_deps = type(cls)._get_old_style_getter_deps(cls, prop_name,<EOL>user_getter)<EOL>def _getter(self, deps=_deps):<EOL><INDENT>return user_getter(self, prop_name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_getter = user_getter<EOL><DEDENT>return _getter<EOL><DEDENT>def _getter(self): <EOL><INDENT>return getattr(self, PROP_NAME % {'<STR_LIT>' : prop_name})<EOL><DEDENT>return _getter<EOL>
Returns a function wich is a getter for a property. prop_name is the name off the property. user_getter is an optional function doing the work. If specified, that function will be called instead of getting the attribute whose name is in 'prop_name'. If user_getter is specified with a False value for getter_takes_name (default), than the method is used to get the value of the property. If True is specified for getter_takes_name, then the user_getter is called by passing the property name (i.e. it is considered a general method which receive the property name whose value has to be returned.)
f2899:c0:m8
def get_setter(cls, prop_name, <EOL>user_setter=None, setter_takes_name=False,<EOL>user_getter=None, getter_takes_name=False):
if user_setter:<EOL><INDENT>if setter_takes_name:<EOL><INDENT>def _setter(self, val):<EOL><INDENT>return user_setter(self, prop_name, val)<EOL><DEDENT><DEDENT>else: _setter = user_setter<EOL>return _setter<EOL><DEDENT>def _setter(self, val): <EOL><INDENT>setattr(self, PROP_NAME % {'<STR_LIT>' : prop_name}, val)<EOL>return<EOL><DEDENT>return _setter<EOL>
Similar to get_getter, but for setting property values. If user_getter is specified, that it may be used to get the old value of the property before setting it (this is the case in some derived classes' implementation). if getter_takes_name is True and user_getter is not None, than the property name is passed to the given getter to retrieve the property value.
f2899:c0:m9
def get_getter(cls, prop_name, <EOL>user_getter=None, getter_takes_name=False):
has_prop_variable = cls.has_prop_attribute(prop_name)<EOL>has_specific_getter = hasattr(cls, GET_PROP_NAME %{'<STR_LIT>' : prop_name})<EOL>has_general_getter = hasattr(cls, GET_GENERIC_NAME)<EOL>if not (has_prop_variable or<EOL>has_specific_getter or<EOL>has_general_getter or<EOL>user_getter):<EOL><INDENT>return None<EOL><DEDENT>if has_prop_variable:<EOL><INDENT>if has_specific_getter or user_getter:<EOL><INDENT>logger.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"% (cls.__module__, cls.__name__, prop_name))<EOL><DEDENT>user_getter = None<EOL>getter_takes_name = False<EOL><DEDENT>else:<EOL><INDENT>if user_getter:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if has_specific_getter:<EOL><INDENT>_getter = getattr(cls, GET_PROP_NAME %{'<STR_LIT>' : prop_name})<EOL>_deps = type(cls)._get_old_style_getter_deps(cls,<EOL>prop_name,<EOL>_getter)<EOL>def __getter(self, deps=_deps):<EOL><INDENT>_getter = getattr(self, GET_PROP_NAME %{'<STR_LIT>' : prop_name})<EOL>return _getter()<EOL><DEDENT>user_getter = __getter<EOL>getter_takes_name = False<EOL><DEDENT>else:<EOL><INDENT>assert has_general_getter<EOL>_getter = getattr(cls, GET_GENERIC_NAME)<EOL>_deps = type(cls)._get_old_style_getter_deps(cls,<EOL>prop_name,<EOL>_getter)<EOL>def __getter(self, name, deps=_deps):<EOL><INDENT>_getter = getattr(self, GET_GENERIC_NAME)<EOL>return _getter(name)<EOL><DEDENT>user_getter = __getter<EOL>getter_takes_name = True<EOL><DEDENT><DEDENT><DEDENT>return PropertyMeta.get_getter(cls, prop_name, user_getter,<EOL>getter_takes_name)<EOL>
This implementation returns the PROP_NAME value if there exists such property. Otherwise there must exist a logical getter (user_getter) which the value is taken from. If no getter is found, None is returned (i.e. the property cannot be created)
f2899:c1:m1
def get_setter(cls, prop_name, <EOL>user_setter=None, setter_takes_name=False,<EOL>user_getter=None, getter_takes_name=False):
has_prop_variable = cls.has_prop_attribute(prop_name)<EOL>has_specific_setter = hasattr(cls, SET_PROP_NAME %{'<STR_LIT>' : prop_name})<EOL>has_general_setter = hasattr(cls, SET_GENERIC_NAME)<EOL>if not (has_prop_variable or<EOL>has_specific_setter or<EOL>has_general_setter or<EOL>user_setter):<EOL><INDENT>return None<EOL><DEDENT>if has_prop_variable:<EOL><INDENT>if has_specific_setter or user_setter:<EOL><INDENT>logger.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %(cls.__module__, cls.__name__, prop_name))<EOL><DEDENT>user_setter = user_getter = None<EOL>setter_takes_name = getter_takes_name = False<EOL><DEDENT>else:<EOL><INDENT>if user_setter:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if has_specific_setter:<EOL><INDENT>def __setter(self, val):<EOL><INDENT>_setter = getattr(self, SET_PROP_NAME %{'<STR_LIT>' : prop_name})<EOL>_setter(val)<EOL>return<EOL><DEDENT>user_setter = __setter<EOL>setter_takes_name = False<EOL><DEDENT>else:<EOL><INDENT>assert has_general_setter<EOL>def __setter(self, name, val):<EOL><INDENT>_setter = getattr(self, SET_GENERIC_NAME)<EOL>_setter(name, val)<EOL>return<EOL><DEDENT>user_setter = __setter<EOL>setter_takes_name = True<EOL><DEDENT><DEDENT><DEDENT>_inner_setter = PropertyMeta.get_setter(cls, prop_name,<EOL>user_setter, setter_takes_name,<EOL>user_getter, getter_takes_name)<EOL>_inner_getter = type(cls).get_getter(cls, prop_name,<EOL>user_getter, getter_takes_name)<EOL>def _setter(self, val):<EOL><INDENT>curr_frame = len(self._notify_stack)<EOL>if prop_name not in self._notify_stack:<EOL><INDENT>self._notify_stack.append(prop_name)<EOL><DEDENT>old = _inner_getter(self)<EOL>new = type(self).create_value(prop_name, val, self)<EOL>olds = self.__before_property_value_change__(prop_name) ifself._has_observer() else ()<EOL>self._notify_stack.extend(<EOL>map(operator.itemgetter(<NUM_LIT:1>), olds))<EOL>_inner_setter(self, new)<EOL>if type(self).check_value_change(old, new):<EOL><INDENT>self._reset_property_notification(prop_name, old)<EOL><DEDENT>self.notify_property_value_change(prop_name, old, val)<EOL>self.__after_property_value_change__(prop_name, olds)<EOL>del self._notify_stack[curr_frame:]<EOL><DEDENT>return _setter<EOL>
The setter follows the rules of the getter. First search for property variable, then logical custom setter. If no setter is found, None is returned (i.e. the property is read-only.)
f2899:c1:m2
def get_setter(cls, prop_name, <EOL>user_setter=None, setter_takes_name=False,<EOL>user_getter=None, getter_takes_name=False):
_inner_setter = ObservablePropertyMeta.get_setter(cls, prop_name,<EOL>user_setter, setter_takes_name,<EOL>user_getter, getter_takes_name)<EOL>def _setter(self, val):<EOL><INDENT>self._prop_lock.acquire()<EOL>_inner_setter(self, val)<EOL>self._prop_lock.release()<EOL><DEDENT>return _setter<EOL>
The setter follows the rules of the getter. First search for property variable, then logical custom getter/setter pair methods
f2899:c2:m1
def getmembers(_object, _predicate):
<EOL>observers = []<EOL>for key in dir(_object):<EOL><INDENT>try: m = getattr(_object, key)<EOL>except AttributeError: continue<EOL>if _predicate(m): observers.append((key, m))<EOL>pass<EOL><DEDENT>return observers<EOL>
This is an implementation of inspect.getmembers, as in some versions of python it may be buggy. See issue at http://bugs.python.org/issue1785
f2900:m0
def cast_value(val, totype):
t = type(val)<EOL>if issubclass(t, totype):<EOL><INDENT>return val <EOL><DEDENT>if issubclass(totype, bytes):<EOL><INDENT>return bytes(val)<EOL><DEDENT>if issubclass(totype, str):<EOL><INDENT>return str(val)<EOL><DEDENT>if issubclass(totype, bool):<EOL><INDENT>if issubclass(t, str):<EOL><INDENT>_v = val.lower()<EOL>if _v in ("<STR_LIT:true>", "<STR_LIT:yes>", "<STR_LIT:y>"):<EOL><INDENT>return True<EOL><DEDENT>if _v in ("<STR_LIT:false>", "<STR_LIT>", "<STR_LIT:n>"):<EOL><INDENT>return False<EOL><DEDENT>raise TypeError("<STR_LIT>" + str(val) +<EOL>"<STR_LIT>" + str(t) +<EOL>"<STR_LIT>" + str(totype))<EOL><DEDENT><DEDENT>if (issubclass(totype, (int, float)) and<EOL>issubclass(t, (bytes, str, int, float))):<EOL><INDENT>if val:<EOL><INDENT>return totype(float(val))<EOL><DEDENT>else:<EOL><INDENT>return totype(<NUM_LIT:0>)<EOL><DEDENT><DEDENT>raise TypeError("<STR_LIT>" + str(val) +<EOL>"<STR_LIT>" + str(t) +<EOL>"<STR_LIT>" + str(totype))<EOL>
Take a value and return it in a different type. If not possible raise :exc:`TypeError`. *val* an arbitrary object. *totype* a class, e.g. :class:`str`. .. note:: Casting the empty string to a numeric type returns zero.
f2900:m1
def __posix_relpath(path, start=os.curdir):
if not path: raise ValueError("<STR_LIT>")<EOL>start_list = os.path.abspath(start).split(os.sep)<EOL>path_list = os.path.abspath(path).split(os.sep)<EOL>i = len(os.path.commonprefix([start_list, path_list]))<EOL>rel_list = [os.pardir] * (len(start_list)-i) + path_list[i:]<EOL>if not rel_list: return os.curdir<EOL>return os.path.join(*rel_list)<EOL>
Return a relative version of a path
f2900:m2
def __nt_relpath(path, start=os.curdir):
if not path: raise ValueError("<STR_LIT>")<EOL>start_list = os.path.abspath(start).split(os.sep)<EOL>path_list = os.path.abspath(path).split(os.sep)<EOL>if start_list[<NUM_LIT:0>].lower() != path_list[<NUM_LIT:0>].lower():<EOL><INDENT>unc_path, rest = os.path.splitunc(path)<EOL>unc_start, rest = os.path.splitunc(start)<EOL>if bool(unc_path) ^ bool(unc_start):<EOL><INDENT>raise ValueError("<STR_LIT>"% (path, start))<EOL><DEDENT>else: raise ValueError("<STR_LIT>"% (path_list[<NUM_LIT:0>], start_list[<NUM_LIT:0>]))<EOL><DEDENT>for i in range(min(len(start_list), len(path_list))):<EOL><INDENT>if start_list[i].lower() != path_list[i].lower():<EOL><INDENT>break<EOL><DEDENT>else: i += <NUM_LIT:1><EOL>pass<EOL><DEDENT>rel_list = [os.pardir] * (len(start_list)-i) + path_list[i:]<EOL>if not rel_list: return os.curdir<EOL>return os.path.join(*rel_list)<EOL>
Return a relative version of a path
f2900:m3
def with_metaclass(meta, *bases):
<EOL>class metaclass(meta):<EOL><INDENT>def __new__(cls, name, this_bases, d):<EOL><INDENT>return meta(name, bases, d)<EOL><DEDENT><DEDENT>return type.__new__(metaclass, '<STR_LIT>', (), {})<EOL>
Create a base class with a metaclass.
f2901:m0
def add_metaclass(metaclass):
def wrapper(cls):<EOL><INDENT>orig_vars = cls.__dict__.copy()<EOL>slots = orig_vars.get('<STR_LIT>')<EOL>if slots is not None:<EOL><INDENT>if isinstance(slots, str):<EOL><INDENT>slots = [slots]<EOL><DEDENT>for slots_var in slots:<EOL><INDENT>orig_vars.pop(slots_var)<EOL><DEDENT><DEDENT>orig_vars.pop('<STR_LIT>', None)<EOL>orig_vars.pop('<STR_LIT>', None)<EOL>return metaclass(cls.__name__, cls.__bases__, orig_vars)<EOL><DEDENT>return wrapper<EOL>
Class decorator for creating a class with a metaclass.
f2901:m1
def good_decorator(decorator):
def new_decorator(f):<EOL><INDENT>g = decorator(f)<EOL>g.__name__ = f.__name__<EOL>g.__doc__ = f.__doc__<EOL>g.__dict__.update(f.__dict__)<EOL>return g<EOL><DEDENT>new_decorator.__name__ = decorator.__name__<EOL>new_decorator.__doc__ = decorator.__doc__<EOL>new_decorator.__dict__.update(decorator.__dict__)<EOL>return new_decorator<EOL>
This decorator makes decorators behave well wrt to decorated functions names, doc, etc.
f2902:m0
def good_classmethod_decorator(decorator):
def new_decorator(cls, f):<EOL><INDENT>g = decorator(cls, f)<EOL>g.__name__ = f.__name__<EOL>g.__doc__ = f.__doc__<EOL>g.__dict__.update(f.__dict__)<EOL>return g<EOL><DEDENT>new_decorator.__name__ = decorator.__name__<EOL>new_decorator.__doc__ = decorator.__doc__<EOL>new_decorator.__dict__.update(decorator.__dict__)<EOL>return new_decorator<EOL>
This decorator makes class method decorators behave well wrt to decorated class method names, doc, etc.
f2902:m1
def good_decorator_accepting_args(decorator):
def new_decorator(*f, **k):<EOL><INDENT>g = decorator(*f, **k)<EOL>if <NUM_LIT:1> == len(f) and isinstance(f[<NUM_LIT:0>], types.FunctionType):<EOL><INDENT>g.__name__ = f[<NUM_LIT:0>].__name__<EOL>g.__doc__ = f[<NUM_LIT:0>].__doc__<EOL>g.__dict__.update(f[<NUM_LIT:0>].__dict__)<EOL>pass<EOL><DEDENT>return g<EOL><DEDENT>new_decorator.__name__ = decorator.__name__<EOL>new_decorator.__doc__ = decorator.__doc__<EOL>new_decorator.__dict__.update(decorator.__dict__)<EOL>new_decorator.__module__ = decorator.__module__<EOL>return new_decorator<EOL>
This decorator makes decorators behave well wrt to decorated functions names, doc, etc. Differently from good_decorator, this accepts decorators possibly receiving arguments and keyword arguments. This decorato can be used indifferently with class methods and functions.
f2902:m2
def generate_project(self):
<EOL>if not self.name or not self.destdir ornot os.path.isdir(self.destdir):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>_log("<STR_LIT>" % self.name)<EOL>_log("<STR_LIT>" % self.destdir)<EOL>top = os.path.join(self.destdir, self.name)<EOL>src = os.path.join(top, self.src_name)<EOL>resources = os.path.join(top, self.res_name)<EOL>utils = os.path.join(src, "<STR_LIT>")<EOL>if self.complex:<EOL><INDENT>models = os.path.join(src, "<STR_LIT>")<EOL>ctrls = os.path.join(src, "<STR_LIT>")<EOL>views = os.path.join(src, "<STR_LIT>")<EOL><DEDENT>else: models = ctrls = views = src<EOL>res = self.__generate_tree(top, src, resources, models, ctrls, views, utils)<EOL>res = self.__generate_classes(models, ctrls, views) or res<EOL>res = self.__mksrc(os.path.join(utils, "<STR_LIT>"), templates.glob) or res<EOL>if self.complex: self.templ.update({'<STR_LIT>' : "<STR_LIT>",<EOL>'<STR_LIT>' : "<STR_LIT>",<EOL>'<STR_LIT>' : "<STR_LIT>"})<EOL>else: self.templ.update({'<STR_LIT>' : "<STR_LIT>",<EOL>'<STR_LIT>' : "<STR_LIT>",<EOL>'<STR_LIT>' : "<STR_LIT>"})<EOL>res = self.__mksrc(os.path.join(top, "<STR_LIT>" % self.name), templates.main) or res<EOL>if self.builder:<EOL><INDENT>res = self.__generate_builder(resources) or res<EOL><DEDENT>if self.dist_gtkmvc3: res = self.__copy_framework(os.path.join(resources, "<STR_LIT>")) or res<EOL>if not res: _log("<STR_LIT>")<EOL>else: _log("<STR_LIT>")<EOL>return res<EOL>
Generate the whole project. Returns True if at least one file has been generated, False otherwise.
f2908:c0:m1
def __generate_tree(self, top, src, resources, models, ctrls, views, utils):
res = self.__mkdir(top)<EOL>for fn in (src, models, ctrls, views, utils): res = self.__mkpkg(fn) or res<EOL>res = self.__mkdir(resources) or res<EOL>res = self.__mkdir(os.path.join(resources, "<STR_LIT>", "<STR_LIT>")) or res<EOL>res = self.__mkdir(os.path.join(resources, "<STR_LIT>", "<STR_LIT>")) or res<EOL>res = self.__mkdir(os.path.join(resources, "<STR_LIT>")) or res<EOL>return res<EOL>
Creates directories and packages
f2908:c0:m2
def iternames():
for i in range(<NUM_LIT:2>, <NUM_LIT:8>) + [<NUM_LIT:1>]:<EOL><INDENT>yield locale.nl_langinfo(getattr(locale, '<STR_LIT>' % i))<EOL><DEDENT>
Monday...Sunday
f2912:m0
def begin_grouping(self):
self._open.append(UndoGroup())<EOL>
Each undo operation has to be in a group. Groups can be nested.
f2915:c1:m3
def can_redo(self):
return bool(self._redo)<EOL>
Are there actions to redo?
f2915:c1:m4
def can_undo(self):
return bool(self._undo) or bool(self._open and self._open[<NUM_LIT:0>])<EOL>
Are there actions to undo?
f2915:c1:m5
def end_grouping(self):
close = self._open.pop()<EOL>if not close:<EOL><INDENT>return<EOL><DEDENT>if self._open:<EOL><INDENT>self._open[-<NUM_LIT:1>].extend(close)<EOL><DEDENT>elif self._undoing:<EOL><INDENT>self._redo.append(close)<EOL><DEDENT>else:<EOL><INDENT>self._undo.append(close)<EOL><DEDENT>self.notify()<EOL>
Raises IndexError when no group is open.
f2915:c1:m6
def grouping_level(self):
return len(self._open)<EOL>
How many groups are open?
f2915:c1:m7
def is_redoing(self):
return self._redoing<EOL>
Are we performing a redo?
f2915:c1:m8
def is_undoing(self):
return self._undoing<EOL>
Are we performing an undo?
f2915:c1:m9
def redo(self):
if self._undoing or self._redoing:<EOL><INDENT>raise RuntimeError<EOL><DEDENT>if not self._redo:<EOL><INDENT>return<EOL><DEDENT>group = self._redo.pop()<EOL>self._redoing = True<EOL>self.begin_grouping()<EOL>group.perform()<EOL>self.set_action_name(group.name)<EOL>self.end_grouping()<EOL>self._redoing = False<EOL>self.notify()<EOL>
Performs the top group on the redo stack, if present. Creates an undo group with the same name. Raises RuntimeError if called while undoing.
f2915:c1:m10
def redo_action_name(self):
if self._redo:<EOL><INDENT>return self._redo[-<NUM_LIT:1>].name<EOL><DEDENT>return "<STR_LIT>"<EOL>
The name of the top group on the redo stack, or an empty string.
f2915:c1:m11
def register(self, func, *args, **kwargs):
self._open[-<NUM_LIT:1>].append(UndoOperation(func, *args, **kwargs))<EOL>if not (self._undoing or self._redoing):<EOL><INDENT>self._redo = []<EOL><DEDENT>self.notify()<EOL>
Record an undo operation. Also clears the redo stack. Raises IndexError when no group is open.
f2915:c1:m12
def set_action_name(self, name):
if self._open and name is not None:<EOL><INDENT>self._open[-<NUM_LIT:1>].name = name<EOL>self.notify()<EOL><DEDENT>
Set the name of the top group, if present.
f2915:c1:m13
def undo(self):
if self.grouping_level() == <NUM_LIT:1>:<EOL><INDENT>self.end_grouping()<EOL><DEDENT>if self._open:<EOL><INDENT>raise IndexError<EOL><DEDENT>self.undo_nested_group()<EOL>self.notify()<EOL>
Raises IndexError if more than one group is open, otherwise closes it and invokes undo_nested_group.
f2915:c1:m14
def undo_action_name(self):
if self._open:<EOL><INDENT>return self._open[-<NUM_LIT:1>].name<EOL><DEDENT>elif self._undo:<EOL><INDENT>return self._undo[-<NUM_LIT:1>].name<EOL><DEDENT>return "<STR_LIT>"<EOL>
The name of the top group on the undo stack, or an empty string.
f2915:c1:m15
def undo_nested_group(self):
if self._undoing or self._redoing:<EOL><INDENT>raise RuntimeError<EOL><DEDENT>if self._open:<EOL><INDENT>group = self._open.pop()<EOL><DEDENT>elif self._undo:<EOL><INDENT>group = self._undo.pop()<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>self._undoing = True<EOL>self.begin_grouping()<EOL>group.perform()<EOL>self.set_action_name(group.name)<EOL>self.end_grouping()<EOL>self._undoing = False<EOL>self.notify()<EOL>
Performs the last group opened, or the top group on the undo stack. Creates a redo group with the same name.
f2915:c1:m16
def __init__(self, name, label, tooltip, *args):
gtk.Action.__init__(self, name, label, tooltip, None)<EOL>self._value = <NUM_LIT:0><EOL>self._args_for_toolitem = args<EOL>self._changed_handlers = {}<EOL>self.set_tool_item_type(SpinToolItem)<EOL>return<EOL>
Create a new SpinToolAction instance. @param args: arguments to be passed to the SpinToolItem class constructor. @type args: list
f2924:c1:m0
def do_create_tool_item(self):
proxy = SpinToolItem(*self._args_for_toolitem)<EOL>self.connect_proxy(proxy)<EOL>return proxy<EOL>
This is called by the UIManager when it is time to instantiate the proxy
f2924:c1:m2
def set_value(self, value):
self._value = value<EOL>for proxy in self.get_proxies():<EOL><INDENT>proxy.handler_block(self._changed_handlers[proxy])<EOL>proxy.set_value(self._value)<EOL>proxy.handler_unblock(self._changed_handlers[proxy])<EOL>pass<EOL><DEDENT>self.emit('<STR_LIT>')<EOL>return<EOL>
Set value to action.
f2924:c1:m4
def get_value(self):
return self._value<EOL>
Set value to action.
f2924:c1:m5
def __init__(self, model, view):
Controller.__init__(self, model, view)<EOL>return<EOL>
Contructor. model will be accessible via the member 'self.model'. View registration is also performed.
f2931:c0:m0
def on_button1_clicked(self, button):
self.model.set_next_message()<EOL>return<EOL>
Handles the signal clicked for button1. Changes the model.
f2931:c0:m2
@Controller.observe("<STR_LIT>", assign=True)<EOL><INDENT>def value_change(self, model, name, info):<DEDENT>
msg = self.model.get_message(info.new)<EOL>self.view.set_msg(msg)<EOL>return<EOL>
The model is changed and the view must be updated
f2931:c0:m3
def enable_rb2(self, flag):
self['<STR_LIT>'].set_sensitive(flag)<EOL>return<EOL>
enables/disables all widgets regarding rb2
f2943:c0:m0
def __init__(self, widget, property, model=None):
gtkmvc3.Observer.__init__(self)<EOL>self.busy = False<EOL>self.widget = widget<EOL>widget.connect('<STR_LIT>', self.widget_notification)<EOL>widget.connect('<STR_LIT>', self.widget_notification)<EOL>self.property = property<EOL>self.observe(self.model_notification, property, assign=True)<EOL>self.model = None<EOL>self.set_model(model)<EOL>
*widget* a `gtk.Entry` instance. *property* a string (may not contain dots) *model* optionally call `set_model` with this.
f2951:c0:m0
def set_model(self, model):
if self.model:<EOL><INDENT>self.model.unregister_observer(self)<EOL><DEDENT>self.model = model<EOL>if self.model:<EOL><INDENT>self.model.register_observer(self)<EOL>self.model_notification()<EOL><DEDENT>else:<EOL><INDENT>self.set_widget(None)<EOL><DEDENT>self.widget.set_sensitive(bool(self.model))<EOL>
*model* a `Model` instance, or None.
f2951:c0:m7
def __init__(self, cls):
gtk.ListStore.__init__(self, object)<EOL>events.listen(self.__on_updated, cls, events.RowUpdatedSignal)<EOL>events.listen(self.__on_created, cls, events.RowCreatedSignal)<EOL>events.listen(self.__on_destroy, cls, events.RowDestroySignal)<EOL>for obj in cls.select():<EOL><INDENT>self.append((obj,))<EOL><DEDENT>
Represent all rows of the :class:`SQLObject` passed, at all times. This causes them to remain in memory, so use with care.
f2952:c0:m0
def enable_rb2(self, flag):
self['<STR_LIT>'].set_sensitive(flag)<EOL>return<EOL>
enables/disables all widgets regarding rb2
f2954:c0:m0
def __getitem__(self, name):
if name[<NUM_LIT:0>] == "<STR_LIT:/>":<EOL><INDENT>return self.manager.get_widget(name)<EOL><DEDENT>return self.items[name]<EOL>
Also accepts widget paths for the internal UIManager. To get Actions you must use their name, not their path.
f2965:c0:m1
def connect_signals(self, target):
if self.connected:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.builder.connect_signals(target)<EOL>self.connected = True<EOL>
This is deprecated. Pass your controller to connect signals the old way.
f2965:c0:m4
def __init__(self, arg, *args, **kwargs):
_Abstract.__init__(self, arg, *args, **kwargs)<EOL>if self.toplevel.flags() & gtk.TOPLEVEL:<EOL><INDENT>raise TypeError<EOL><DEDENT>
When creating widgets in code, pass two arguments: a :class:`gtk.Widget` instance and a string naming it. To use GtkBuilder you pass the path to the XML file and between one and many names of widgets you'd like to load, e.g. "box1", "liststore1". The first will become our :meth:`get_toplevel`.
f2965:c1:m0
def reparent(self, other, name):
<EOL>old = self.toplevel.get_parent()<EOL>if old:<EOL><INDENT>old.remove(self.toplevel)<EOL><DEDENT>new = other[name]<EOL>new.add(self.toplevel)<EOL>
Remove :meth:`get_toplevel` from any current parent and add it to *other[name]*.
f2965:c1:m1
def __init__(self, arg, *args, **kwargs):
_Abstract.__init__(self, arg, *args, **kwargs)<EOL>if not self.toplevel.flags() & gtk.TOPLEVEL:<EOL><INDENT>raise TypeError<EOL><DEDENT>
Works just like :class:`Widget`. Using GtkBuilder you can load more than one window into an instance, but this makes re-using your views harder and may be removed in the future. The limitations of these classes reflect best practices. If you don't like them write your view from scratch. As long as you use handler="class" all the controller expects is __getitem__ and __iter__.
f2965:c2:m0
def add_ui_from_file(self, path):
self.manager.add_ui_from_file(path)<EOL>
When you add ActionGroups through Glade or :meth:`__setitem__` they are automatically inserted into an internal UIManager. Its accelerators are set up with our toplevel window. All you have to do is use this method to load some XML and pack the widgets.
f2965:c2:m1
def set_transient_for(self, other):
self.toplevel.set_transient_for(other.get_toplevel())<EOL>
*other* a :class:`Window` instance.
f2965:c2:m2
def run(self):
self.busy = True<EOL>for i in range(<NUM_LIT:9>):<EOL><INDENT>self.counter += <NUM_LIT:1><EOL>time.sleep(<NUM_LIT:0.5>)<EOL>pass<EOL><DEDENT>self.counter += <NUM_LIT:1><EOL>self.busy = False<EOL>return<EOL>
This method is run by a separated thread
f2975:c0:m2
def _parse_css_color(color):
if color.startswith("<STR_LIT>") and color.endswith('<STR_LIT:)>'):<EOL><INDENT>r, g, b = [int(c)*<NUM_LIT> for c in color[<NUM_LIT:4>:-<NUM_LIT:1>].split('<STR_LIT:U+002C>')]<EOL>return gtk.gdk.Color(r, g, b)<EOL><DEDENT>else:<EOL><INDENT>return gtk.gdk.color_parse(color)<EOL><DEDENT>
_parse_css_color(css_color) -> gtk.gdk.Color
f2978:m0
def _parse_length(self, value, font_relative, callback, *args):
if value.endswith('<STR_LIT:%>'):<EOL><INDENT>frac = float(value[:-<NUM_LIT:1>])/<NUM_LIT:100><EOL>if font_relative:<EOL><INDENT>attrs = self._get_current_attributes()<EOL>font_size = attrs.font.get_size() / pango.SCALE<EOL>callback(frac*display_resolution*font_size, *args)<EOL><DEDENT>else:<EOL><INDENT>alloc = self.textview.get_allocation()<EOL>self.__parse_length_frac_size_allocate(self.textview, alloc,<EOL>frac, callback, args)<EOL>self.textview.connect("<STR_LIT>",<EOL>self.__parse_length_frac_size_allocate,<EOL>frac, callback, args)<EOL><DEDENT><DEDENT>elif value.endswith('<STR_LIT>'): <EOL><INDENT>callback(float(value[:-<NUM_LIT:2>])*display_resolution, *args)<EOL><DEDENT>elif value.endswith('<STR_LIT>'): <EOL><INDENT>attrs = self._get_current_attributes()<EOL>font_size = attrs.font.get_size() / pango.SCALE<EOL>callback(float(value[:-<NUM_LIT:2>])*display_resolution*font_size, *args)<EOL><DEDENT>elif value.endswith('<STR_LIT>'): <EOL><INDENT>attrs = self._get_current_attributes()<EOL>font_size = attrs.font.get_size() / pango.SCALE<EOL>callback(float(value[:-<NUM_LIT:2>])*display_resolution*font_size, *args)<EOL><DEDENT>elif value.endswith('<STR_LIT>'): <EOL><INDENT>callback(int(value[:-<NUM_LIT:2>]), *args)<EOL><DEDENT>else:<EOL><INDENT>warnings.warn("<STR_LIT>" % value)<EOL><DEDENT>
Parse/calc length, converting to pixels, calls callback(length, *args) when the length is first computed or changes
f2978:c0:m4