signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def set_date_range(self, start=None, end=None):
|
start = self._start if start is None else pd.to_datetime(start)<EOL>end = self._end if end is None else pd.to_datetime(end)<EOL>self._update(self.prices.loc[start:end])<EOL>
|
Update date range of stats, charts, etc. If None then
the original date is used. So to reset to the original
range, just call with no args.
Args:
* start (date): start date
* end (end): end date
|
f2810:c0:m5
|
def display(self):
|
print('<STR_LIT>' % (self.name, self.start, self.end))<EOL>if type(self.rf) is float:<EOL><INDENT>print('<STR_LIT>' % (fmtp(self.rf)))<EOL><DEDENT>print('<STR_LIT>')<EOL>data = [[fmtp(self.total_return), fmtn(self.daily_sharpe),<EOL>fmtp(self.cagr), fmtp(self.max_drawdown)]]<EOL>print(tabulate(data, headers=['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>']))<EOL>print('<STR_LIT>')<EOL>data = [[fmtp(self.mtd), fmtp(self.three_month), fmtp(self.six_month),<EOL>fmtp(self.ytd), fmtp(self.one_year), fmtp(self.three_year),<EOL>fmtp(self.five_year), fmtp(self.ten_year),<EOL>fmtp(self.incep)]]<EOL>print(tabulate(data,<EOL>headers=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']))<EOL>print('<STR_LIT>')<EOL>data = [<EOL>['<STR_LIT>', fmtn(self.daily_sharpe), fmtn(self.monthly_sharpe),<EOL>fmtn(self.yearly_sharpe)],<EOL>['<STR_LIT>', fmtp(self.daily_mean), fmtp(self.monthly_mean),<EOL>fmtp(self.yearly_mean)],<EOL>['<STR_LIT>', fmtp(self.daily_vol), fmtp(self.monthly_vol),<EOL>fmtp(self.yearly_vol)],<EOL>['<STR_LIT>', fmtn(self.daily_skew), fmtn(self.monthly_skew),<EOL>fmtn(self.yearly_skew)],<EOL>['<STR_LIT>', fmtn(self.daily_kurt), fmtn(self.monthly_kurt),<EOL>fmtn(self.yearly_kurt)],<EOL>['<STR_LIT>', fmtp(self.best_day), fmtp(self.best_month),<EOL>fmtp(self.best_year)],<EOL>['<STR_LIT>', fmtp(self.worst_day), fmtp(self.worst_month),<EOL>fmtp(self.worst_year)]]<EOL>print(tabulate(data, headers=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']))<EOL>print('<STR_LIT>')<EOL>data = [<EOL>[fmtp(self.max_drawdown), fmtp(self.avg_drawdown),<EOL>fmtn(self.avg_drawdown_days)]]<EOL>print(tabulate(data, headers=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']))<EOL>print('<STR_LIT>')<EOL>data = [['<STR_LIT>', fmtp(self.avg_up_month)],<EOL>['<STR_LIT>', fmtp(self.avg_down_month)],<EOL>['<STR_LIT>', fmtp(self.win_year_perc)],<EOL>['<STR_LIT>', fmtp(self.twelve_month_win_perc)]]<EOL>print(tabulate(data))<EOL>
|
Displays an overview containing descriptive stats for the Series
provided.
|
f2810:c0:m6
|
def display_monthly_returns(self):
|
data = [['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']]<EOL>for k in self.return_table.index:<EOL><INDENT>r = self.return_table.loc[k].values<EOL>data.append([k] + [fmtpn(x) for x in r])<EOL><DEDENT>print(tabulate(data, headers='<STR_LIT>'))<EOL>
|
Display a table containing monthly returns and ytd returns
for every year in range.
|
f2810:c0:m7
|
def display_lookback_returns(self):
|
return self.lookback_returns.map('<STR_LIT>'.format)<EOL>
|
Displays the current lookback returns.
|
f2810:c0:m8
|
def plot(self, freq=None, figsize=(<NUM_LIT:15>, <NUM_LIT:5>), title=None,<EOL>logy=False, **kwargs):
|
if title is None:<EOL><INDENT>title = self._get_default_plot_title(<EOL>self.name, freq, '<STR_LIT>')<EOL><DEDENT>ser = self._get_series(freq)<EOL>return ser.plot(figsize=figsize, title=title, logy=logy, **kwargs)<EOL>
|
Helper function for plotting the series.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* logy (bool): log-scale for y axis
* kwargs: passed to pandas' plot method
|
f2810:c0:m10
|
def plot_histogram(self, freq=None, figsize=(<NUM_LIT:15>, <NUM_LIT:5>), title=None,<EOL>bins=<NUM_LIT:20>, **kwargs):
|
if title is None:<EOL><INDENT>title = self._get_default_plot_title(<EOL>self.name, freq, '<STR_LIT>')<EOL><DEDENT>ser = self._get_series(freq).to_returns().dropna()<EOL>plt.figure(figsize=figsize)<EOL>ax = ser.hist(bins=bins, figsize=figsize, normed=True, **kwargs)<EOL>ax.set_title(title)<EOL>plt.axvline(<NUM_LIT:0>, linewidth=<NUM_LIT:4>)<EOL>return ser.plot(kind='<STR_LIT>')<EOL>
|
Plots a histogram of returns given a return frequency.
Args:
* freq (str): Data frequency used for display purposes.
This will dictate the type of returns
(daily returns, monthly, ...)
Refer to pandas docs for valid period strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* bins (int): number of bins for the histogram
* kwargs: passed to pandas' hist method
|
f2810:c0:m11
|
def to_csv(self, sep='<STR_LIT:U+002C>', path=None):
|
stats = self._stats()<EOL>data = []<EOL>first_row = ['<STR_LIT>', self.name]<EOL>data.append(sep.join(first_row))<EOL>for stat in stats:<EOL><INDENT>k, n, f = stat<EOL>if k is None:<EOL><INDENT>row = ['<STR_LIT>'] * len(data[<NUM_LIT:0>])<EOL>data.append(sep.join(row))<EOL>continue<EOL><DEDENT>elif k == '<STR_LIT>' and not type(self.rf) == float:<EOL><INDENT>continue<EOL><DEDENT>row = [n]<EOL>raw = getattr(self, k)<EOL>if f is None:<EOL><INDENT>row.append(raw)<EOL><DEDENT>elif f == '<STR_LIT:p>':<EOL><INDENT>row.append(fmtp(raw))<EOL><DEDENT>elif f == '<STR_LIT:n>':<EOL><INDENT>row.append(fmtn(raw))<EOL><DEDENT>elif f == '<STR_LIT>':<EOL><INDENT>row.append(raw.strftime('<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>' % f)<EOL><DEDENT>data.append(sep.join(row))<EOL><DEDENT>res = '<STR_LIT:\n>'.join(data)<EOL>if path is not None:<EOL><INDENT>with open(path, '<STR_LIT:w>') as fl:<EOL><INDENT>fl.write(res)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return res<EOL><DEDENT>
|
Returns a CSV string with appropriate formatting.
If path is not None, the string will be saved to file
at path.
Args:
* sep (char): Separator
* path (str): If None, CSV string returned. Else file written
to specified path.
|
f2810:c0:m14
|
def set_riskfree_rate(self, rf):
|
for key in self._names:<EOL><INDENT>self[key].set_riskfree_rate(rf)<EOL><DEDENT>self._update_stats()<EOL>
|
Set annual `risk-free rate <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ property and calculate properly annualized
monthly and daily rates. Then performance stats are recalculated.
Affects only those instances of PerformanceStats that are children of
this GroupStats object.
Args:
* rf (float, Series): Annual risk-free rate or risk-free rate price series
|
f2810:c1:m7
|
def set_date_range(self, start=None, end=None):
|
start = self._start if start is None else pd.to_datetime(start)<EOL>end = self._end if end is None else pd.to_datetime(end)<EOL>self._update(self._prices.loc[start:end])<EOL>
|
Update date range of stats, charts, etc. If None then
the original date range is used. So to reset to the original
range, just call with no args.
Args:
* start (date): start date
* end (end): end date
|
f2810:c1:m8
|
def display(self):
|
data = []<EOL>first_row = ['<STR_LIT>']<EOL>first_row.extend(self._names)<EOL>data.append(first_row)<EOL>stats = self._stats()<EOL>for stat in stats:<EOL><INDENT>k, n, f = stat<EOL>if k is None:<EOL><INDENT>row = ['<STR_LIT>'] * len(data[<NUM_LIT:0>])<EOL>data.append(row)<EOL>continue<EOL><DEDENT>row = [n]<EOL>for key in self._names:<EOL><INDENT>raw = getattr(self[key], k)<EOL>if k == '<STR_LIT>' and not type(raw) == float:<EOL><INDENT>row.append(np.nan)<EOL><DEDENT>elif f is None:<EOL><INDENT>row.append(raw)<EOL><DEDENT>elif f == '<STR_LIT:p>':<EOL><INDENT>row.append(fmtp(raw))<EOL><DEDENT>elif f == '<STR_LIT:n>':<EOL><INDENT>row.append(fmtn(raw))<EOL><DEDENT>elif f == '<STR_LIT>':<EOL><INDENT>row.append(raw.strftime('<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>' % f)<EOL><DEDENT><DEDENT>data.append(row)<EOL><DEDENT>print(tabulate(data, headers='<STR_LIT>'))<EOL>
|
Display summary stats table.
|
f2810:c1:m9
|
def display_lookback_returns(self):
|
return self.lookback_returns.apply(<EOL>lambda x: x.map('<STR_LIT>'.format), axis=<NUM_LIT:1>)<EOL>
|
Displays the current lookback returns for each series.
|
f2810:c1:m10
|
def plot(self, freq=None, figsize=(<NUM_LIT:15>, <NUM_LIT:5>), title=None,<EOL>logy=False, **kwargs):
|
if title is None:<EOL><INDENT>title = self._get_default_plot_title(<EOL>freq, '<STR_LIT>')<EOL><DEDENT>ser = self._get_series(freq).rebase()<EOL>return ser.plot(figsize=figsize, logy=logy,<EOL>title=title, **kwargs)<EOL>
|
Helper function for plotting the series.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* logy (bool): log-scale for y axis
* kwargs: passed to pandas' plot method
|
f2810:c1:m11
|
def plot_scatter_matrix(self, freq=None, title=None,<EOL>figsize=(<NUM_LIT:10>, <NUM_LIT:10>), **kwargs):
|
if title is None:<EOL><INDENT>title = self._get_default_plot_title(<EOL>freq, '<STR_LIT>')<EOL><DEDENT>plt.figure()<EOL>ser = self._get_series(freq).to_returns().dropna()<EOL>pd.scatter_matrix(ser, figsize=figsize, **kwargs)<EOL>return plt.suptitle(title)<EOL>
|
Wrapper around pandas' scatter_matrix.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* kwargs: passed to pandas' scatter_matrix method
|
f2810:c1:m12
|
def plot_histograms(self, freq=None, title=None,<EOL>figsize=(<NUM_LIT:10>, <NUM_LIT:10>), **kwargs):
|
if title is None:<EOL><INDENT>title = self._get_default_plot_title(<EOL>freq, '<STR_LIT>')<EOL><DEDENT>plt.figure()<EOL>ser = self._get_series(freq).to_returns().dropna()<EOL>ser.hist(figsize=figsize, **kwargs)<EOL>return plt.suptitle(title)<EOL>
|
Wrapper around pandas' hist.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* kwargs: passed to pandas' hist method
|
f2810:c1:m13
|
def plot_correlation(self, freq=None, title=None,<EOL>figsize=(<NUM_LIT:12>, <NUM_LIT:6>), **kwargs):
|
if title is None:<EOL><INDENT>title = self._get_default_plot_title(<EOL>freq, '<STR_LIT>')<EOL><DEDENT>rets = self._get_series(freq).to_returns().dropna()<EOL>return rets.plot_corr_heatmap(title=title, figsize=figsize, **kwargs)<EOL>
|
Utility function to plot correlations.
Args:
* freq (str): Pandas data frequency alias string
* title (str): Plot title
* figsize (tuple (x,y)): figure size
* kwargs: passed to Pandas' plot_corr_heatmap function
|
f2810:c1:m14
|
def to_csv(self, sep='<STR_LIT:U+002C>', path=None):
|
data = []<EOL>first_row = ['<STR_LIT>']<EOL>first_row.extend(self._names)<EOL>data.append(sep.join(first_row))<EOL>stats = self._stats()<EOL>for stat in stats:<EOL><INDENT>k, n, f = stat<EOL>if k is None:<EOL><INDENT>row = ['<STR_LIT>'] * len(data[<NUM_LIT:0>])<EOL>data.append(sep.join(row))<EOL>continue<EOL><DEDENT>row = [n]<EOL>for key in self._names:<EOL><INDENT>raw = getattr(self[key], k)<EOL>if f is None:<EOL><INDENT>row.append(raw)<EOL><DEDENT>elif f == '<STR_LIT:p>':<EOL><INDENT>row.append(fmtp(raw))<EOL><DEDENT>elif f == '<STR_LIT:n>':<EOL><INDENT>row.append(fmtn(raw))<EOL><DEDENT>elif f == '<STR_LIT>':<EOL><INDENT>row.append(raw.strftime('<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>' % f)<EOL><DEDENT><DEDENT>data.append(sep.join(row))<EOL><DEDENT>res = '<STR_LIT:\n>'.join(data)<EOL>if path is not None:<EOL><INDENT>with open(path, '<STR_LIT:w>') as fl:<EOL><INDENT>fl.write(res)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return res<EOL><DEDENT>
|
Returns a CSV string with appropriate formatting.
If path is not None, the string will be saved to file
at path.
Args:
* sep (char): Separator
* path (str): If None, CSV string returned. Else file
written to specified path.
|
f2810:c1:m16
|
def memoize(f, refresh_keyword='<STR_LIT>'):
|
f.mcache = {}<EOL>f.mrefresh_keyword = refresh_keyword<EOL>return decorator.decorator(_memoize, f)<EOL>
|
Memoize decorator. The refresh keyword is the keyword
used to bypass the cache (in the function call).
|
f2811:m1
|
def parse_arg(arg):
|
<EOL>if type(arg) == str:<EOL><INDENT>arg = arg.strip()<EOL>if '<STR_LIT:U+002C>' in arg:<EOL><INDENT>arg = arg.split('<STR_LIT:U+002C>')<EOL>arg = [x.strip() for x in arg]<EOL><DEDENT>else:<EOL><INDENT>arg = [arg]<EOL><DEDENT><DEDENT>return arg<EOL>
|
Parses arguments for convenience. Argument can be a
csv list ('a,b,c'), a string, a list, a tuple.
Returns a list.
|
f2811:m2
|
def clean_ticker(ticker):
|
pattern = re.compile('<STR_LIT>')<EOL>res = pattern.sub('<STR_LIT>', ticker.split('<STR_LIT:U+0020>')[<NUM_LIT:0>])<EOL>return res.lower()<EOL>
|
Cleans a ticker for easier use throughout MoneyTree
Splits by space and only keeps first bit. Also removes
any characters that are not letters. Returns as lowercase.
>>> clean_ticker('^VIX')
'vix'
>>> clean_ticker('SPX Index')
'spx'
|
f2811:m3
|
def clean_tickers(tickers):
|
return [clean_ticker(x) for x in tickers]<EOL>
|
Maps clean_ticker over tickers.
|
f2811:m4
|
def fmtp(number):
|
if np.isnan(number):<EOL><INDENT>return '<STR_LIT:->'<EOL><DEDENT>return format(number, '<STR_LIT>')<EOL>
|
Formatting helper - percent
|
f2811:m5
|
def fmtpn(number):
|
if np.isnan(number):<EOL><INDENT>return '<STR_LIT:->'<EOL><DEDENT>return format(number * <NUM_LIT:100>, '<STR_LIT>')<EOL>
|
Formatting helper - percent no % sign
|
f2811:m6
|
def fmtn(number):
|
if np.isnan(number):<EOL><INDENT>return '<STR_LIT:->'<EOL><DEDENT>return format(number, '<STR_LIT>')<EOL>
|
Formatting helper - float
|
f2811:m7
|
def scale(val, src, dst):
|
if val < src[<NUM_LIT:0>]:<EOL><INDENT>return dst[<NUM_LIT:0>]<EOL><DEDENT>if val > src[<NUM_LIT:1>]:<EOL><INDENT>return dst[<NUM_LIT:1>]<EOL><DEDENT>return ((val - src[<NUM_LIT:0>]) / (src[<NUM_LIT:1>] - src[<NUM_LIT:0>])) * (dst[<NUM_LIT:1>] - dst[<NUM_LIT:0>]) + dst[<NUM_LIT:0>]<EOL>
|
Scale value from src range to dst range.
If value outside bounds, it is clipped and set to
the low or high bound of dst.
Ex:
scale(0, (0.0, 99.0), (-1.0, 1.0)) == -1.0
scale(-5, (0.0, 99.0), (-1.0, 1.0)) == -1.0
|
f2811:m9
|
def as_format(item, format_str='<STR_LIT>'):
|
if isinstance(item, pd.Series):<EOL><INDENT>return item.map(lambda x: format(x, format_str))<EOL><DEDENT>elif isinstance(item, pd.DataFrame):<EOL><INDENT>return item.applymap(lambda x: format(x, format_str))<EOL><DEDENT>
|
Map a format string over a pandas object.
|
f2811:m11
|
def method1(self, arg1, arg2):
|
pass<EOL>
|
Does stuff with args.
Demo method1 - this method does stuff. Interesting right?
Args:
arg1 (type): The first arg needed to do stuff.
arg2 (type): The second arg needed to do stuff.
Returns:
str - stuff string
|
f2815:c0:m1
|
def convert_notebooks():
|
convert_status = call(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>if convert_status != <NUM_LIT:0>:<EOL><INDENT>raise SystemError('<STR_LIT>' % convert_status)<EOL><DEDENT>notebooks = [x for x in os.listdir('<STR_LIT:.>') if '<STR_LIT>'<EOL>in x and os.path.isfile(x)]<EOL>names = [os.path.splitext(x)[<NUM_LIT:0>] for x in notebooks]<EOL>for i in range(len(notebooks)):<EOL><INDENT>name = names[i]<EOL>notebook = notebooks[i]<EOL>print('<STR_LIT>' % (name, notebook))<EOL>sdir = '<STR_LIT>' % name<EOL>statics = os.listdir(sdir)<EOL>statics = [os.path.join(sdir, x) for x in statics]<EOL>[shutil.copy(x, '<STR_LIT>') for x in statics]<EOL>shutil.rmtree(sdir)<EOL>rst_file = '<STR_LIT>' % name<EOL>print('<STR_LIT>' % rst_file)<EOL>data = None<EOL>with open(rst_file, '<STR_LIT:r>') as f:<EOL><INDENT>data = f.read()<EOL><DEDENT>if data is not None:<EOL><INDENT>with open(rst_file, '<STR_LIT:w>') as f:<EOL><INDENT>data = re.sub('<STR_LIT>' % sdir, '<STR_LIT>', data)<EOL>f.write(data)<EOL><DEDENT><DEDENT>lines = None<EOL>with open(rst_file, '<STR_LIT:r>') as f:<EOL><INDENT>lines = f.readlines()<EOL><DEDENT>if lines is not None:<EOL><INDENT>n = len(lines)<EOL>i = <NUM_LIT:0><EOL>rawWatch = False<EOL>while i < n:<EOL><INDENT>line = lines[i]<EOL>if '<STR_LIT>' in line:<EOL><INDENT>lines.insert(i + <NUM_LIT:1>, '<STR_LIT>')<EOL>n += <NUM_LIT:1><EOL><DEDENT>elif '<STR_LIT>' in line:<EOL><INDENT>lines.insert(i + <NUM_LIT:1>, '<STR_LIT>')<EOL>n += <NUM_LIT:1><EOL><DEDENT>elif '<STR_LIT>' in line:<EOL><INDENT>rawWatch = True<EOL><DEDENT>if rawWatch:<EOL><INDENT>if '<STR_LIT>' in line:<EOL><INDENT>line = line.replace('<STR_LIT>', '<STR_LIT>')<EOL>lines[i] = line<EOL>rawWatch = False<EOL><DEDENT><DEDENT>i += <NUM_LIT:1><EOL><DEDENT>with open(rst_file, '<STR_LIT:w>') as f:<EOL><INDENT>f.writelines(lines)<EOL><DEDENT><DEDENT><DEDENT>
|
Converts IPython Notebooks to proper .rst files and moves static
content to the _static directory.
|
f2816:m0
|
def get_html_theme_path():
|
cur_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))<EOL>return cur_dir<EOL>
|
Returns list of HTML theme paths.
|
f2816:m1
|
def adapterTest(self):
|
self.c.adapt()<EOL>self.assertEqual(Gtk.ToolbarStyle.TEXT, self.v["<STR_LIT:bar>"].get_style())<EOL>self.v["<STR_LIT:bar>"].set_style(Gtk.ToolbarStyle.ICONS)<EOL>self.assertEqual(Gtk.ToolbarStyle.ICONS, self.m.bar)<EOL>
|
Not called by the unittest.main()
|
f2825:c1:m2
|
def has_item(x):
|
if hasattr(x, '<STR_LIT>'):<EOL><INDENT>x = list(x.values())<EOL><DEDENT>if hasattr(x, '<STR_LIT>'):<EOL><INDENT>for i in x:<EOL><INDENT>if has_item(i):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL><DEDENT>return True<EOL>
|
Return whether any non-sequence occurs in a given recursive sequence.
|
f2831:m0
|
def change_data_source_value(self):
|
old = self.data_source<EOL>self.data_source += <NUM_LIT:1> <EOL>self.external = self.data_source <EOL>return<EOL>
|
This simulates a change in the external data source. For
the sake of simplicity, this is called from the controller
when a button is pressed, but in a real example this got
called by the external data source
|
f2839:c0:m3
|
def __contains__(self, key):
|
try:<EOL><INDENT>return bool(self[key])<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT>
|
If __contains__ isn't implemented the `key in view` operator uses
__iter__ which omits some types of widgets (that don't implement
get_name). __getitem__ does not have that problem.
|
f2840:c1:m0
|
def _find_widget_match(self, prop_name):
|
self.called = True<EOL>if prop_name not in self.view:<EOL><INDENT>raise ValueError<EOL><DEDENT>return prop_name<EOL>
|
Don't try matching widgets because it doesn't work for some types.
|
f2840:c2:m0
|
def adapt(self):
|
a = gtkmvc3.adapters.Adapter(self.m, '<STR_LIT:date>')<EOL>def setter(c, d):<EOL><INDENT>c.select_month(d.month - <NUM_LIT:1>, d.year)<EOL>c.select_day(d.day)<EOL><DEDENT>a.connect_widget(<EOL>self.v['<STR_LIT>'], getter=lambda w: datetime.date(*w.get_date()),<EOL>setter=setter, signal='<STR_LIT>')<EOL>self.c.adapt(a)<EOL>
|
Controller handles Calendar specially and creates three
RoUserClassAdapter instances. This is only necessary for datetime
instances, as regular Adapter doesn't give the getter access to the
old model value to copy the time. Still, datetime may occur in the
wild, adapted to a Calendar and two or three SpinButton.
|
f2853:c2:m0
|
def RadioAction__notify_current_value(widget, handler, *args):
|
group = widget.get_group() or [widget]<EOL>active = [action for action in group if action.get_active()]<EOL>if len(active) == <NUM_LIT:1>:<EOL><INDENT>handler(widget, None, *args)<EOL><DEDENT>
|
With GTK 2.22.1 the first time a group of RadioButton changes neither
changed nor notify::current-value are emitted:
https://bugzilla.gnome.org/show_bug.cgi?id=615458
We work around this by using the toggled signal. Unfortunately this is
emitted twice per button per change:
http://faq.pygtk.org/index.py?req=show&file=faq09.004.htp
Also during the first emission both the old and the new selected button
have their active property set.
We use this to filter out the first emission and call the real handler
on the second one.
Unlike the notify signal, toggled is emitted even if the active button is
just clicked again. Since the handler is probably an Adapter, and filters
out spurious notifications, we don't work around that here.
More severly, it is impossible to instantiate gobject.GParamSpec in
Python, so we just pass None as the second argument. Again this doesn't
matter for Adapter.
|
f2878:m0
|
def connect(widget, signal, handler, *args):
|
if (isinstance(widget, Gtk.RadioAction) and<EOL>signal == "<STR_LIT>"):<EOL><INDENT>widget.connect(<EOL>"<STR_LIT>", RadioAction__notify_current_value, handler, *args)<EOL><DEDENT>else:<EOL><INDENT>widget.connect(signal, handler, *args)<EOL><DEDENT>
|
Use this instead of *widget*.connect if you want GTKMVC to
automatically work around some known GTK bugs.
|
f2878:m1
|
def __init__(self, top=None,<EOL>parent=None,<EOL>builder=None):
|
self.manualWidgets = {}<EOL>self.autoWidgets = {}<EOL>self.__autoWidgets_calculated = False<EOL>self.glade_xmlWidgets = []<EOL>_top = top if top else self.top<EOL>wids = ((_top,) if _top is None or isinstance(_top, str)<EOL>else _top) <EOL>if hasattr(self, "<STR_LIT>"):<EOL><INDENT>raise ViewError("<STR_LIT>"<EOL>"<STR_LIT>" % self.__class__)<EOL><DEDENT>_builder = builder if builder else self.builder<EOL>if _builder is not None:<EOL><INDENT>if isinstance(_builder, Gtk.Builder):<EOL><INDENT>self._builder = _builder<EOL><DEDENT>else:<EOL><INDENT>self._builder = Gtk.Builder()<EOL>self._builder.add_from_file(_builder)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._builder = None <EOL><DEDENT>if _top is not None:<EOL><INDENT>if len(wids) > <NUM_LIT:1>:<EOL><INDENT>self.m_topWidget = []<EOL>for i in range(<NUM_LIT:0>, len(wids)):<EOL><INDENT>self.m_topWidget.append(self[wids[i]])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.m_topWidget = self[wids[<NUM_LIT:0>]]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.m_topWidget = None<EOL><DEDENT>if parent is not None:<EOL><INDENT>self.set_parent_view(parent)<EOL><DEDENT>self.builder_pending_callbacks = {}<EOL>self.builder_connected = False<EOL>
|
Only the first three may be given as positional arguments. If an
argument is empty a class attribute of the same name is used. This
does not work for *parent*.
*top* is a string or a list of strings containing the names of our top
level widgets. When using libglade only their children are loaded.
This does NOT work with *builder*, each instance will create every
window in the file.
*parent* is used to call :meth:`set_parent_view`.
*builder* is a path to an XML file defining widgets in GtkBuilder
format. It can also be a :class:`Gtk.Builder` instance which already
contains widgets. This is useful for internationalisation or if you
want to break one XML file up into multiple views. Do not use that
variant with class attributes, or all instances of this view will share
one set of widgets.
.. deprecated:: 1.99.1
In future versions the functionality will be split into the new
class :class:`ManualView` and its child :class:`BuilderView`.
|
f2882:c0:m0
|
def __getitem__(self, key):
|
wid = None<EOL>if key in self.manualWidgets:<EOL><INDENT>wid = self.manualWidgets[key]<EOL><DEDENT>if wid is None:<EOL><INDENT>if key in self.autoWidgets:<EOL><INDENT>wid = self.autoWidgets[key]<EOL><DEDENT>else:<EOL><INDENT>if wid is None and self._builder is not None:<EOL><INDENT>wid = self._builder.get_object(key)<EOL>if wid is not None:<EOL><INDENT>self.autoWidgets[key] = wid<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if not wid:<EOL><INDENT>raise KeyError(key)<EOL><DEDENT>return wid<EOL>
|
Return the widget named *key* or raise KeyError.
.. versionchanged:: 1.99.2
Used to return None when the widget wasn't found.
|
f2882:c0:m1
|
def __setitem__(self, key, wid):
|
self.manualWidgets[key] = wid<EOL>if self.m_topWidget is None:<EOL><INDENT>self.m_topWidget = wid<EOL><DEDENT>
|
Add a widget. This overrides widgets of the same name that were loaded
fom XML. It does not affect GTK container/child relations.
If no top widget is known, this sets it.
|
f2882:c0:m2
|
def show(self):
|
top = self.get_top_widget()<EOL>if isinstance(top, (list, tuple)):<EOL><INDENT>for t in top:<EOL><INDENT>if t is not None:<EOL><INDENT>t.show()<EOL><DEDENT><DEDENT><DEDENT>elif top is not None:<EOL><INDENT>top.show_all()<EOL><DEDENT>
|
Call `show()` on each top widget or `show_all()` if only one is known.
Otherwise does nothing.
|
f2882:c0:m3
|
def hide(self):
|
top = self.get_top_widget()<EOL>if isinstance(top, (list, tuple)):<EOL><INDENT>for t in top:<EOL><INDENT>if t is not None:<EOL><INDENT>t.hide_all()<EOL><DEDENT><DEDENT><DEDENT>elif top is not None:<EOL><INDENT>top.hide_all()<EOL><DEDENT>
|
Call `hide_all()` on all known top widgets.
|
f2882:c0:m4
|
def get_top_widget(self):
|
return self.m_topWidget<EOL>
|
Return a widget or list of widgets.
|
f2882:c0:m5
|
def set_parent_view(self, parent_view):
|
top = self.get_top_widget()<EOL>if isinstance(top, (list, tuple)):<EOL><INDENT>for t in top:<EOL><INDENT>if t is not None:<EOL><INDENT>t.set_transient_for(parent_view.get_top_widget())<EOL><DEDENT><DEDENT><DEDENT>elif top is not None:<EOL><INDENT>top.set_transient_for(parent_view.get_top_widget())<EOL><DEDENT>
|
Set ``self.``:meth:`get_top_widget` transient for
``parent_view.get_top_widget()``.
|
f2882:c0:m6
|
def set_transient(self, transient_view):
|
top = self.get_top_widget()<EOL>if isinstance(top, (list, tuple)):<EOL><INDENT>for t in top:<EOL><INDENT>if t is not None:<EOL><INDENT>transient_view.get_top_widget().set_transient_for(t)<EOL><DEDENT><DEDENT><DEDENT>elif top is not None:<EOL><INDENT>transient_view.get_top_widget().set_transient_for(top)<EOL><DEDENT>
|
Set ``transient_view.get_top_widget()`` transient for
``self.``:meth:`get_top_widget`.
|
f2882:c0:m7
|
def __builder_connect_pending_signals(self):
|
class _MultiHandlersProxy (object):<EOL><INDENT>def __init__(self, funcs): self.funcs = funcs<EOL>def __call__(self, *args, **kwargs):<EOL><INDENT>for func in self.funcs:<EOL><INDENT>res = func(*args, **kwargs)<EOL><DEDENT>return res<EOL><DEDENT><DEDENT>final_dict = {n: (v.pop() if len(v) == <NUM_LIT:1><EOL>else _MultiHandlersProxy(v))<EOL>for n, v in self.builder_pending_callbacks.items()}<EOL>self._builder.connect_signals(final_dict)<EOL>self.builder_connected = True<EOL>self.builder_pending_callbacks = {}<EOL>
|
Called internally to actually make the internal Gtk.Builder
instance connect all signals found in controllers controlling
self.
|
f2882:c0:m9
|
def _builder_connect_signals(self, _dict):
|
assert not self.builder_connected, "<STR_LIT>"<EOL>if _dict and not self.builder_pending_callbacks:<EOL><INDENT>GLib.idle_add(self.__builder_connect_pending_signals)<EOL><DEDENT>for n, v in _dict.items():<EOL><INDENT>if n not in self.builder_pending_callbacks:<EOL><INDENT>_set = set()<EOL>self.builder_pending_callbacks[n] = _set<EOL><DEDENT>else:<EOL><INDENT>_set = self.builder_pending_callbacks[n]<EOL><DEDENT>_set.add(v)<EOL><DEDENT>
|
Called by controllers which want to autoconnect their
handlers with signals declared in internal Gtk.Builder.
This method accumulates handlers, and books signal
autoconnection later on the idle of the next occurring gtk
loop. After the autoconnection is done, this method cannot be
called anymore.
|
f2882:c0:m10
|
def __iter__(self):
|
<EOL>self.__extract_autoWidgets()<EOL>for i in itertools.chain(self.manualWidgets, self.autoWidgets):<EOL><INDENT>yield i<EOL><DEDENT>
|
Yield names of widgets added with :meth:`__setitem__` and
those loaded from XML.
.. note::
In case of name conflicts the result contains duplicates, but only
the manually added widget is accessible via :meth:`__getitem__`.
|
f2882:c0:m11
|
def __extract_autoWidgets(self):
|
if self.__autoWidgets_calculated: return<EOL>if self._builder is not None:<EOL><INDENT>for wid in self._builder.get_objects():<EOL><INDENT>try:<EOL><INDENT>name = Gtk.Buildable.get_name(wid)<EOL><DEDENT>except TypeError:<EOL><INDENT>continue<EOL><DEDENT>if name in self.autoWidgets and self.autoWidgets[name] != wid:<EOL><INDENT>raise ViewError("<STR_LIT>"<EOL>"<STR_LIT>" % name)<EOL><DEDENT>self.autoWidgets[name] = wid<EOL><DEDENT><DEDENT>self.__autowidgets_calculated = True<EOL>
|
Extract autoWidgets map if needed, out of the glade
specifications and gtk builder
|
f2882:c0:m12
|
def partition(string, sep):
|
p = string.split(sep, <NUM_LIT:1>)<EOL>if len(p) == <NUM_LIT:2>:<EOL><INDENT>return p[<NUM_LIT:0>], sep, p[<NUM_LIT:1>]<EOL><DEDENT>return string, '<STR_LIT>', '<STR_LIT>'<EOL>
|
New in Python 2.5 as str.partition(sep)
|
f2883:m0
|
def __init__(self, model, view, spurious=False, auto_adapt=False,<EOL>handlers="<STR_LIT>"):
|
<EOL>if view in (True, False):<EOL><INDENT>raise NotImplementedError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>Observer.__init__(self, model, spurious)<EOL>self.handlers = handlers or self.handlers<EOL>self.model = model<EOL>self.view = None<EOL>self.__adapters = []<EOL>self.__user_props = set()<EOL>self.__auto_adapt = auto_adapt<EOL>GLib.idle_add(self._idle_register_view, view,<EOL>priority=GLib.PRIORITY_HIGH)<EOL>
|
Two positional and three optional keyword arguments.
*model* will have the new instance registered as an observer.
It is made available as an attribute.
*view* may contain signal connections loaded from XML. The handler
methods have to exist in this class.
*spurious* denotes whether notifications in this class will be called
if a property of *model* is set to the same value it already has.
*auto_adapt* denotes whether to call :meth:`adapt` with no arguments
as part of the view registration process.
*handlers* denotes where signal connections are made. Possible values
are "glade" (the default) and "class". In the latter case all
controller methods with a name like `on_<widget>__<signal>` (e.g.
:meth:`on_my_window__delete_event`, note the two underscores) are
connected automatically.
View registration consists of connecting signal handlers,
:meth:`register_view` and :meth:`register_adapters`, and is scheduled
with the GTK main loop. It happens as soon as possible but after the
constructor returns. When it starts *view* is available as an
attribute.
|
f2883:c0:m0
|
def _idle_register_view(self, view):
|
assert(self.view is None)<EOL>self.view = view<EOL>if self.handlers == "<STR_LIT:class>":<EOL><INDENT>for name in dir(self):<EOL><INDENT>when, _, what = partition(name, '<STR_LIT:_>')<EOL>widget, _, signal = partition(what, '<STR_LIT>')<EOL>if when == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>view[widget].connect(signal, getattr(self, name))<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.warn("<STR_LIT>", name)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif self.handlers == "<STR_LIT>":<EOL><INDENT>self.__autoconnect_signals()<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>"<EOL>"<STR_LIT>" % self.handlers)<EOL><DEDENT>self.register_view(view)<EOL>self.register_adapters()<EOL>if self.__auto_adapt: self.adapt()<EOL>return False<EOL>
|
Internal method that calls register_view
|
f2883:c0:m1
|
def register_view(self, view):
|
assert(self.model is not None)<EOL>assert(self.view is not None)<EOL>
|
This does nothing. Subclasses can override it to connect signals
manually or modify widgets loaded from XML, like adding columns to a
TreeView. No super call necessary.
*view* is a shortcut for ``self.view``.
|
f2883:c0:m2
|
def register_adapters(self):
|
assert(self.model is not None)<EOL>assert(self.view is not None)<EOL>
|
This does nothing. Subclasses can override it to create adapters.
No super call necessary.
|
f2883:c0:m3
|
def setup_columns(self):
|
for name in self.view:<EOL><INDENT>w = self.view[name]<EOL>if isinstance(w, Gtk.TreeView):<EOL><INDENT>m = w.get_model()<EOL>for c in w.get_columns():<EOL><INDENT>self.setup_column(c, model=m)<EOL><DEDENT><DEDENT><DEDENT>
|
Search the view for :class:`TreeView` instances and call
:meth:`setup_column` on all their columns.
.. note::
This is a convenience function. It is never called by the framework.
You are free to repurpose it in subclasses.
For editing to work, the widget must already be connected to a model.
If you don't use :class:`ListStoreModel` this can be done in Glade,
however a `bug <https://bugzilla.gnome.org/show_bug.cgi?id=597095>`_
makes versions prior to 3.7.0 (released March 10th, 2010) remove
Python columns on save. If you want to correct the XML manually, it
should look like this::
<object class="GtkListStore" id="liststore1">
<columns>
<column type="PyObject"/>
</columns>
</object>
|
f2883:c0:m4
|
def setup_column(self, widget, column=<NUM_LIT:0>, attribute=None, renderer=None,<EOL>property=None, from_python=None, to_python=None, model=None):<EOL>
|
if isinstance(widget, str):<EOL><INDENT>widget = self.view[widget]<EOL><DEDENT>if not model and isinstance(self.model, Gtk.TreeModel):<EOL><INDENT>model = self.model<EOL><DEDENT>return setup_column(widget, column=column, attribute=attribute,<EOL>renderer=renderer, property=property, from_python=from_python,<EOL>to_python=to_python, model=model)<EOL>
|
Set up a :class:`TreeView` to display attributes of Python objects
stored in its :class:`TreeModel`.
This assumes that :class:`TreeViewColumn` instances have already
been added and :class:`CellRenderer` instances packed into them.
Both can be done in Glade.
*model* is the instance displayed by the widget. You only need to pass
this if you set *renderer* to be editable.
If you use sorting or filtering this may not be the actual data store,
but all tree paths and column indexes are relative to this.
Defaults to our model.
*widget* is a column, or a string naming one in our view.
*column* is an integer addressing the column in *model* that holds your
objects.
*attribute* is a string naming an object attribute to display. Defaults
to the name of *widget*.
*renderer* defaults to the first one found in *widget*.
*property* is a string naming the property of *renderer* to set. If not
given this is guessed based on the type of *renderer*.
*from_python* is a callable. It gets passed a value from the object and
must return it in a format suitable for *renderer*. If not given this
is guessed based on *property*.
*to_python* is a callable. It gets passed a value from *renderer* and
must return it in a format suitable for the attribute. If not given a
cast to the type of the previous attribute value is attempted.
If you need more flexibility, like setting multiple properties, setting
your own cell data function will override the internal one.
Returns an integer you can use to disconnect the internal editing
callback from *renderer*, or None.
.. versionadded:: 1.99.2
|
f2883:c0:m5
|
def adapt(self, *args, **kwargs):
|
<EOL>n = len(args)<EOL>flavour = kwargs.get("<STR_LIT>", None)<EOL>if n==<NUM_LIT:0>:<EOL><INDENT>adapters = []<EOL>props = self.model.get_properties()<EOL>for prop_name in (p for p in props<EOL>if p not in self.__user_props):<EOL><INDENT>try: wid_name = self._find_widget_match(prop_name)<EOL>except TooManyCandidatesError as e:<EOL><INDENT>raise e<EOL><DEDENT>except ValueError as e:<EOL><INDENT>if e.args:<EOL><INDENT>logger.warn(e[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>logger.warn("<STR_LIT>"<EOL>% prop_name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.debug("<STR_LIT>" %(prop_name, wid_name))<EOL>adapters += self.__create_adapters__(prop_name, wid_name, flavour)<EOL><DEDENT><DEDENT><DEDENT>elif n == <NUM_LIT:1>: <EOL><INDENT>if isinstance(args[<NUM_LIT:0>], Adapter): adapters = (args[<NUM_LIT:0>],)<EOL>elif isinstance(args[<NUM_LIT:0>], str):<EOL><INDENT>prop_name = args[<NUM_LIT:0>]<EOL>wid_name = self._find_widget_match(prop_name)<EOL>adapters = self.__create_adapters__(prop_name, wid_name, flavour)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>elif n == <NUM_LIT:2>: <EOL><INDENT>if not (isinstance(args[<NUM_LIT:0>], str) and<EOL>isinstance(args[<NUM_LIT:1>], str)):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>prop_name, wid_name = args<EOL>adapters = self.__create_adapters__(prop_name, wid_name, flavour)<EOL><DEDENT>elif n == <NUM_LIT:3>:<EOL><INDENT>for arg in args:<EOL><INDENT>if not isinstance(arg, str):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>prop_name, wid_name, gprop_name = args<EOL>ad = Adapter(self.model, prop_name)<EOL>ad.connect_widget(self.view[wid_name],<EOL>getter=lambda w: w.get_property(gprop_name),<EOL>setter=lambda w, v: w.set_property(gprop_name, v),<EOL>signal='<STR_LIT>' % gprop_name,<EOL>flavour=flavour)<EOL>adapters = [ad]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>" % n)<EOL><DEDENT>for ad in adapters:<EOL><INDENT>self.__adapters.append(ad)<EOL>if n > <NUM_LIT:0>: self.__user_props.add(ad.get_property_name())<EOL><DEDENT>
|
There are five ways to call this:
.. method:: adapt()
:noindex:
Take properties from the model for which ``adapt`` has not yet been
called, match them to the view by name, and create adapters fitting
for the respective widget type.
That information comes from :mod:`gtkmvc3.adapters.default`.
See :meth:`_find_widget_match` for name patterns.
.. versionchanged:: 1.99.1
Allow incomplete auto-adaption, meaning properties for which no
widget is found.
.. method:: adapt(ad)
:noindex:
Keep track of manually created adapters for future ``adapt()``
calls.
*ad* is an adapter instance already connected to a widget.
.. method:: adapt(prop_name)
:noindex:
Like ``adapt()`` for a single property.
*prop_name* is a string.
.. method:: adapt(prop_name, wid_name)
:noindex:
Like ``adapt(prop_name)`` but without widget name matching.
*wid_name* has to exist in the view.
.. method:: adapt(prop_name, wid_name, gprop_name)
:noindex:
Like ``adapt(prop_name, wid_name)`` but without using default
adapters. This is useful to adapt secondary properties like
button sensitivity.
*gprop_name* is a string naming a property of the widget. No cast
is attempted, so *prop_name* must match its type exactly.
.. versionadded:: 1.99.2
In all cases, optional keyword argument ``flavour=value``
can be used to specify a particular flavour from those
available in :mod:`gtkmvc3.adapters.default` adapters.
|
f2883:c0:m6
|
def _find_widget_match(self, prop_name):
|
names = []<EOL>for wid_name in self.view:<EOL><INDENT>if wid_name.lower().endswith(prop_name.lower()):<EOL><INDENT>names.append(wid_name)<EOL><DEDENT><DEDENT>if len(names) == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" %(prop_name, names))<EOL><DEDENT>if len(names) > <NUM_LIT:1>:<EOL><INDENT>raise TooManyCandidatesError("<STR_LIT>" %(len(names), prop_name, names))<EOL><DEDENT>return names[<NUM_LIT:0>]<EOL>
|
Used to search ``self.view`` when :meth:`adapt` is not given a widget
name.
*prop_name* is the name of a property in the model.
Returns a string with the best match. Raises
:class:`TooManyCandidatesError` or ``ValueError`` when nothing is
found.
Subclasses can customise this. No super call necessary. The default
implementation converts *prop_name* to lower case and allows prefixes
like ``entry_``.
|
f2883:c0:m7
|
def __autoconnect_signals(self):
|
dic = {}<EOL>for name in dir(self):<EOL><INDENT>method = getattr(self, name)<EOL>if (not isinstance(method, collections.Callable)):<EOL><INDENT>continue<EOL><DEDENT>assert(name not in dic) <EOL>dic[name] = method<EOL><DEDENT>for xml in self.view.glade_xmlWidgets:<EOL><INDENT>xml.signal_autoconnect(dic)<EOL><DEDENT>if self.view._builder is not None:<EOL><INDENT>self.view._builder_connect_signals(dic)<EOL><DEDENT>
|
This is called during view registration, to autoconnect
signals in glade file with methods within the controller
|
f2883:c0:m8
|
def __create_adapters__(self, prop_name, wid_name, flavour=None):
|
res = []<EOL>wid = self.view[wid_name]<EOL>if wid is None:<EOL><INDENT>raise ValueError("<STR_LIT>" % wid_name)<EOL><DEDENT>if isinstance(wid, Gtk.Calendar):<EOL><INDENT>ad = RoUserClassAdapter(self.model, prop_name,<EOL>lambda d: d.year,<EOL>lambda d,y: d.replace(year=y),<EOL>spurious=self.accepts_spurious_change())<EOL>ad.connect_widget(wid, lambda c: c.get_date()[<NUM_LIT:0>],<EOL>lambda c,y: c.select_month(c.get_date()[<NUM_LIT:1>], y),<EOL>"<STR_LIT>", flavour=flavour)<EOL>res.append(ad) <EOL>ad = RoUserClassAdapter(self.model, prop_name,<EOL>lambda d: d.month,<EOL>lambda d,m: d.replace(month=m),<EOL>spurious=self.accepts_spurious_change())<EOL>ad.connect_widget(wid, lambda c: c.get_date()[<NUM_LIT:1>]+<NUM_LIT:1>,<EOL>lambda c,m: c.select_month(m-<NUM_LIT:1>, c.get_date()[<NUM_LIT:0>]),<EOL>"<STR_LIT>", flavour=flavour)<EOL>res.append(ad) <EOL>ad = RoUserClassAdapter(self.model, prop_name,<EOL>lambda d: d.day,<EOL>lambda d,v: d.replace(day=v),<EOL>spurious=self.accepts_spurious_change())<EOL>ad.connect_widget(wid, lambda c: c.get_date()[<NUM_LIT:2>],<EOL>lambda c,d: c.select_day(d),<EOL>"<STR_LIT>", flavour=flavour)<EOL>res.append(ad) <EOL>return res<EOL><DEDENT>try: <EOL><INDENT>if "<STR_LIT:.>" in prop_name:<EOL><INDENT>raise TypeError<EOL><DEDENT>ad = StaticContainerAdapter(self.model, prop_name,<EOL>spurious=self.accepts_spurious_change())<EOL>ad.connect_widget(wid, flavours=flavour)<EOL>res.append(ad)<EOL><DEDENT>except TypeError as e:<EOL><INDENT>ad = Adapter(self.model, prop_name,<EOL>spurious=self.accepts_spurious_change())<EOL>ad.connect_widget(wid, flavour=flavour)<EOL>res.append(ad)<EOL><DEDENT>return res<EOL>
|
Private service that looks at property and widgets types,
and possibly creates one or more (best) fitting adapters
that are returned as a list.
``flavour`` is optionally used when a particular flavour
must be used when seraching in default adapters.
|
f2883:c0:m9
|
def count_leaves(x):
|
if hasattr(x, '<STR_LIT>'):<EOL><INDENT>x = list(x.values())<EOL><DEDENT>if hasattr(x, '<STR_LIT>'):<EOL><INDENT>return sum(map(count_leaves, x))<EOL><DEDENT>return <NUM_LIT:1><EOL>
|
Return the number of non-sequence items in a given recursive sequence.
|
f2884:m0
|
@classmethod<EOL><INDENT>@decorators.good_decorator_accepting_args<EOL>def getter(cls, *args, **kwargs):<DEDENT>
|
@decorators.good_decorator<EOL>def __decorator(_func):<EOL><INDENT>_dict = getattr(cls, metaclasses.LOGICAL_GETTERS_MAP_NAME,<EOL>None)<EOL>if _dict is None:<EOL><INDENT>_dict = dict()<EOL>setattr(cls, metaclasses.LOGICAL_GETTERS_MAP_NAME, _dict)<EOL><DEDENT>if <NUM_LIT:0> == len(names):<EOL><INDENT>if _func.__name__ in _dict:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>_dict[_func.__name__] = cls.__getinfo(_func, False, deps)<EOL><DEDENT>else:<EOL><INDENT>for name in names:<EOL><INDENT>if name in _dict:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>_dict[name] = cls.__getinfo(_func, True, deps)<EOL><DEDENT><DEDENT>return _func<EOL><DEDENT>if <NUM_LIT:1> == len(args) and isinstance(args[<NUM_LIT:0>], types.FunctionType):<EOL><INDENT>names = [] <EOL>deps = () <EOL>return __decorator(args[<NUM_LIT:0>])<EOL><DEDENT>for arg in args:<EOL><INDENT>if not isinstance(arg, str):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>_deps = kwargs.get(metaclasses.KWARG_NAME_DEPS, ())<EOL>if not hasattr(_deps, '<STR_LIT>'):<EOL><INDENT>raise TypeError("<STR_LIT>" %<EOL>metaclasses.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>" %metaclasses.KWARG_NAME_DEPS)<EOL><DEDENT><DEDENT>unsupported = set(kwargs) - set((metaclasses.KWARG_NAME_DEPS,))<EOL>if unsupported:<EOL><INDENT>logger.warn("<STR_LIT>",<EOL>str(unsupported))<EOL><DEDENT>names = args <EOL>deps = _deps <EOL>return __decorator<EOL>
|
Decorate a method as a logical property getter. Comes in two flavours:
.. method:: getter([deps=(name,...)])
:noindex:
Uses the name of the method as the property name.
The method must not require arguments.
.. method:: getter(one, two, ..., [deps=(name,...)])
:noindex:
Takes a variable number of strings as the property
name(s). These may contain wildcards as expanded by :mod:`fnmatch`.
The name of the method does not matter.
The method must take a property name as its sole argument.
For both, `deps` is an iterable of property names, identifying which
are the properties (both logical and concrete) which the
logical property depends on.
.. versionadded:: 1.99.1
Introduced the decorator.
.. versionchanged:: 1.99.2
Added optional *deps* parameter.
|
f2884:c0:m0
|
@classmethod<EOL><INDENT>@decorators.good_decorator_accepting_args<EOL>def setter(cls, *args):<DEDENT>
|
@decorators.good_decorator<EOL>def __decorator(_func):<EOL><INDENT>_dict = getattr(cls, metaclasses.LOGICAL_SETTERS_MAP_NAME,<EOL>None)<EOL>if _dict is None:<EOL><INDENT>_dict = dict()<EOL>setattr(cls, metaclasses.LOGICAL_SETTERS_MAP_NAME,<EOL>_dict)<EOL><DEDENT>if <NUM_LIT:0> == len(names):<EOL><INDENT>if _func.__name__ in _dict:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>_dict[_func.__name__] = cls.__setinfo(_func, False)<EOL><DEDENT>else:<EOL><INDENT>for name in names:<EOL><INDENT>if name in _dict:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>_dict[name] = cls.__setinfo(_func, True)<EOL><DEDENT><DEDENT>return _func<EOL><DEDENT>if <NUM_LIT:1> == len(args) and isinstance(args[<NUM_LIT:0>], types.FunctionType):<EOL><INDENT>names = [] <EOL>return __decorator(args[<NUM_LIT:0>])<EOL><DEDENT>for arg in args:<EOL><INDENT>if not isinstance(arg, str):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>names = args <EOL>return __decorator<EOL>
|
Decorate a method as a logical property setter. The counterpart to
:meth:`getter`. Also comes in two flavours:
.. method:: setter()
:noindex:
Uses the name of the method as the property name.
The method must take one argument, the new value.
.. method:: setter(one, two, ...)
:noindex:
Takes a variable number of strings as the property
name(s). The name of the method does not matter.
The method must take two arguments, the property name and new value.
|
f2884:c0:m1
|
def _calculate_logical_deps(self):
|
self.__log_prop_deps = {} <EOL>_mod_cls = "<STR_LIT>" % (self.__class__.__module__,<EOL>self.__class__.__name__)<EOL>logic_ops = ((name, opr.deps)<EOL>for name, opr in getmembers(type(self),<EOL>x: isinstance(x, metaclasses.ObservablePropertyMeta.LogicalOP)<EOL>))<EOL>for name, deps in logic_ops:<EOL><INDENT>for dep in deps:<EOL><INDENT>if not self.has_property(dep):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (_mod_cls, name, dep))<EOL><DEDENT>rdeps = self.__log_prop_deps.get(dep, [])<EOL>assert name not in rdeps<EOL>rdeps.append(name)<EOL>self.__log_prop_deps[dep] = rdeps<EOL><DEDENT><DEDENT>for name, rdeps in self.__log_prop_deps.items():<EOL><INDENT>logger.debug("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>_mod_cls, name, "<STR_LIT:U+002CU+0020>".join(rdeps))<EOL><DEDENT>graph = dict((prop, frozenset(deps))<EOL>for prop, deps in self.__log_prop_deps.items())<EOL>graph.update((prop, frozenset())<EOL>for prop in functools.reduce(set.union,<EOL>map(set, graph.values()),<EOL>set()) - set(graph.keys()))<EOL>while True:<EOL><INDENT>leaves = frozenset(prop for prop, deps in graph.items()<EOL>if not deps)<EOL>if not leaves:<EOL><INDENT>break<EOL><DEDENT>graph = dict((prop, (deps - leaves))<EOL>for prop, deps in graph.items()<EOL>if prop not in leaves)<EOL><DEDENT>if graph:<EOL><INDENT>raise ValueError("<STR_LIT>"% (_mod_cls, "<STR_LIT:U+002CU+0020>".join(graph.keys())))<EOL><DEDENT>return<EOL>
|
Internal service which calculates dependencies information
based on those given with getters.
The graph has to be reversed, as the getter tells that a
property depends on a set of others, but the model needs to
know how has to be notified (i.e. needs to know which OP is
affected by an OP). Only proximity of edges is considered,
the rest is demanded at runtime)
Result is stored inside internal dict __log_prop_deps which
represents the dependencies graph.
|
f2884:c0:m4
|
def register_property(self, name):
|
if name not in self.__value_notifications:<EOL><INDENT>self.__value_notifications[name] = []<EOL><DEDENT>prop = self.__get_prop_value(name)<EOL>if isinstance(prop, ObsWrapperBase):<EOL><INDENT>prop.__add_model__(self, name)<EOL>if isinstance(prop, Signal):<EOL><INDENT>if name not in self.__signal_notif:<EOL><INDENT>self.__signal_notif[name] = []<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if name not in self.__instance_notif_before:<EOL><INDENT>self.__instance_notif_before[name] = []<EOL><DEDENT>if name not in self.__instance_notif_after:<EOL><INDENT>self.__instance_notif_after[name] = []<EOL><DEDENT><DEDENT><DEDENT>
|
Registers an existing property to be monitored, and sets up
notifiers for notifications.
|
f2884:c0:m5
|
def has_property(self, name):
|
return name in self.get_properties()<EOL>
|
Returns true if given property name refers an observable
property inside self or inside derived classes.
|
f2884:c0:m6
|
def register_observer(self, observer):
|
if observer in self.__observers: return <EOL>assert isinstance(observer, Observer)<EOL>self.__observers.append(observer)<EOL>for key in self.get_properties():<EOL><INDENT>self.__add_observer_notification(observer, key)<EOL><DEDENT>
|
Register given observer among those observers which are
interested in observing the model.
|
f2884:c0:m7
|
def unregister_observer(self, observer):
|
assert isinstance(observer, Observer)<EOL>if observer not in self.__observers:<EOL><INDENT>return<EOL><DEDENT>for key in self.get_properties():<EOL><INDENT>self.__remove_observer_notification(observer, key)<EOL><DEDENT>self.__observers.remove(observer)<EOL>
|
Unregister the given observer that is no longer interested
in observing the model.
|
f2884:c0:m8
|
def _reset_property_notification(self, prop_name, old=None):
|
<EOL>if isinstance(old, ObsWrapperBase):<EOL><INDENT>old.__remove_model__(self, prop_name)<EOL><DEDENT>self.register_property(prop_name)<EOL>for observer in self.__observers:<EOL><INDENT>self.__remove_observer_notification(observer, prop_name)<EOL>self.__add_observer_notification(observer, prop_name)<EOL><DEDENT>
|
Called when it has be done an assignment that changes the
type of a property or the instance of the property has been
changed to a different instance. In this case it must be
unregistered and registered again. Optional parameter old has
to be used when the old value is an instance (derived from
ObsWrapperBase) which needs to unregisters from the model, via
a call to method old.__remove_model__(model, prop_name)
|
f2884:c0:m9
|
def get_properties(self):
|
return getattr(self, metaclasses.ALL_OBS_SET, frozenset())<EOL>
|
All observable properties accessible from this instance.
:rtype: frozenset of strings
|
f2884:c0:m10
|
def __add_observer_notification(self, observer, prop_name):
|
value = self.__get_prop_value(prop_name)<EOL>def getmeth(_format, numargs):<EOL><INDENT>name = _format % prop_name<EOL>meth = getattr(observer, name)<EOL>args, varargs, _, _ = inspect.getargspec(meth)<EOL>if not varargs and len(args) != numargs:<EOL><INDENT>logger.warn("<STR_LIT>"<EOL>"<STR_LIT>", name, numargs)<EOL>raise AttributeError<EOL><DEDENT>return meth<EOL><DEDENT>def add_value(notification, kw=None):<EOL><INDENT>pair = (notification, kw)<EOL>if pair in self.__value_notifications[prop_name]:<EOL><INDENT>return<EOL><DEDENT>logger.debug("<STR_LIT>",<EOL>observer.__class__.__name__, notification.__name__,<EOL>self.__class__.__name__, prop_name)<EOL>self.__value_notifications[prop_name].append(pair)<EOL><DEDENT>def add_before(notification, kw=None):<EOL><INDENT>if (not isinstance(value, ObsWrapperBase) or<EOL>isinstance(value, Signal)):<EOL><INDENT>return<EOL><DEDENT>pair = (notification, kw)<EOL>if pair in self.__instance_notif_before[prop_name]:<EOL><INDENT>return<EOL><DEDENT>logger.debug("<STR_LIT>",<EOL>observer.__class__.__name__, notification.__name__,<EOL>self.__class__.__name__, prop_name)<EOL>self.__instance_notif_before[prop_name].append(pair)<EOL><DEDENT>def add_after(notification, kw=None):<EOL><INDENT>if (not isinstance(value, ObsWrapperBase) or<EOL>isinstance(value, Signal)):<EOL><INDENT>return<EOL><DEDENT>pair = (notification, kw)<EOL>if pair in self.__instance_notif_after[prop_name]:<EOL><INDENT>return<EOL><DEDENT>logger.debug("<STR_LIT>",<EOL>observer.__class__.__name__, notification.__name__,<EOL>self.__class__.__name__, prop_name)<EOL>self.__instance_notif_after[prop_name].append(pair)<EOL><DEDENT>def add_signal(notification, kw=None):<EOL><INDENT>if not isinstance(value, Signal):<EOL><INDENT>return<EOL><DEDENT>pair = (notification, kw)<EOL>if pair in self.__signal_notif[prop_name]:<EOL><INDENT>return<EOL><DEDENT>logger.debug("<STR_LIT>",<EOL>observer.__class__.__name__, notification.__name__,<EOL>self.__class__.__name__, prop_name)<EOL>self.__signal_notif[prop_name].append(pair)<EOL><DEDENT>try: notification = getmeth("<STR_LIT>", <NUM_LIT:3>)<EOL>except AttributeError: pass<EOL>else: add_signal(notification)<EOL>try: notification = getmeth("<STR_LIT>", <NUM_LIT:4>)<EOL>except AttributeError: pass<EOL>else: add_value(notification)<EOL>try: notification = getmeth("<STR_LIT>", <NUM_LIT:6>)<EOL>except AttributeError: pass<EOL>else: add_before(notification)<EOL>try: notification = getmeth("<STR_LIT>", <NUM_LIT:7>)<EOL>except AttributeError: pass<EOL>else: add_after(notification)<EOL>type_to_adding_method = {<EOL>'<STR_LIT>' : add_value,<EOL>'<STR_LIT>' : add_before,<EOL>'<STR_LIT>' : add_after,<EOL>'<STR_LIT>' : add_signal,<EOL>}<EOL>for meth in observer.get_observing_methods(prop_name):<EOL><INDENT>added = False<EOL>kw = observer.get_observing_method_kwargs(prop_name, meth)<EOL>for flag, adding_meth in type_to_adding_method.items():<EOL><INDENT>if flag in kw:<EOL><INDENT>added = True<EOL>adding_meth(meth, kw)<EOL><DEDENT><DEDENT>if not added:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(observer.__class__,<EOL>meth.__name__, prop_name))<EOL><DEDENT><DEDENT>
|
Find observing methods and store them for later notification.
*observer* an instance.
*prop_name* a string.
This checks for magic names as well as methods explicitly added through
decorators or at runtime. In the latter case the type of the
notification is inferred from the number of arguments it takes.
|
f2884:c0:m11
|
def __remove_observer_notification(self, observer, prop_name):
|
def side_effect(seq):<EOL><INDENT>for meth, kw in reversed(seq):<EOL><INDENT>if meth.__self__ is observer:<EOL><INDENT>seq.remove((meth, kw))<EOL>yield meth<EOL><DEDENT><DEDENT><DEDENT>for meth in side_effect(self.__value_notifications.get(prop_name, ())):<EOL><INDENT>logger.debug("<STR_LIT>",<EOL>observer.__class__.__name__, meth.__name__,<EOL>self.__class__.__name__, prop_name)<EOL><DEDENT>for meth in side_effect(self.__signal_notif.get(prop_name, ())):<EOL><INDENT>logger.debug("<STR_LIT>",<EOL>observer.__class__.__name__, meth.__name__,<EOL>self.__class__.__name__, prop_name)<EOL><DEDENT>for meth in side_effect(<EOL>self.__instance_notif_before.get(prop_name, ())):<EOL><INDENT>logger.debug("<STR_LIT>",<EOL>observer.__class__.__name__, meth.__name__,<EOL>self.__class__.__name__, prop_name)<EOL><DEDENT>for meth in side_effect(<EOL>self.__instance_notif_after.get(prop_name, ())):<EOL><INDENT>logger.debug("<STR_LIT>",<EOL>observer.__class__.__name__, meth.__name__,<EOL>self.__class__.__name__, prop_name)<EOL><DEDENT>
|
Remove all stored notifications.
*observer* an instance.
*prop_name* a string.
|
f2884:c0:m12
|
def __notify_observer__(self, observer, method, *args, **kwargs):
|
return method(*args, **kwargs)<EOL>
|
This can be overridden by derived class in order to call
the method in a different manner (for example, in
multithreading, or a rpc, etc.) This implementation simply
calls the given method with the given arguments
|
f2884:c0:m13
|
def __before_property_value_change__(self, prop_name):
|
return tuple((self, name, getattr(self, name))<EOL>for name in self._get_logical_deps(prop_name)<EOL>if name not in self._notify_stack)<EOL>
|
This is called right before the value of a property gets
changed, and before a property change notification is
sent. This is called before calling
notify_property_value_change in order to first collect all the
old values of the properties whose value is declared to be
dependend on this property. Returns a tuple containing the old
values (the values before the assignments to prop_name), among
with other information. The returned tuple has to be passed to
__after_property_value_change__. All this procedure is done by
the setter's code which is generated by the metaclass.
|
f2884:c0:m14
|
def _get_logical_deps(self, prop_name):
|
if prop_name not in self.__log_prop_deps:<EOL><INDENT>return <EOL><DEDENT>alread_visited = set()<EOL>to_be_visited = self.__log_prop_deps[prop_name][:] <EOL>while to_be_visited:<EOL><INDENT>x = to_be_visited.pop(<NUM_LIT:0>)<EOL>if x not in alread_visited:<EOL><INDENT>yield x<EOL>alread_visited.add(x)<EOL>children = self.__log_prop_deps.get(x, [])<EOL>to_be_visited += children<EOL><DEDENT><DEDENT>
|
Returns an iterator over a sequence of property names,
which has to e notified upon any value modification of
prop_name. used internally by __before_property_value_change__
|
f2884:c0:m15
|
def __after_property_value_change__(self, prop_name, old_vals):
|
for model, name, val in old_vals:<EOL><INDENT>model.notify_property_value_change(name, val, getattr(model, name))<EOL><DEDENT>
|
This is called after the value of a property is
changed. This is called while calling
notify_property_value_change in order to notify all the
observers which are interested in observing properties whose
value is declared to be dependend on this property. The
old_vals tuple is the value returned by the previous call to
__before_property_value_change__. All this procedure is done
by the setter's code which is generated by the metaclass.
|
f2884:c0:m16
|
def notify_property_value_change(self, prop_name, old, new):
|
assert prop_name in self.__value_notifications<EOL>for method, kw in self.__value_notifications[prop_name] :<EOL><INDENT>obs = method.__self__<EOL>if kw and "<STR_LIT>" in kw:<EOL><INDENT>spurious = kw['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>spurious = obs.accepts_spurious_change()<EOL><DEDENT>if old != new or spurious:<EOL><INDENT>if kw is None: <EOL><INDENT>self.__notify_observer__(obs, method,<EOL>self, old, new)<EOL><DEDENT>elif '<STR_LIT>' in kw: <EOL><INDENT>self.__notify_observer__(obs, method,<EOL>self, prop_name, old, new)<EOL><DEDENT>else:<EOL><INDENT>info = NTInfo('<STR_LIT>',<EOL>kw, model=self, prop_name=prop_name,<EOL>old=old, new=new)<EOL>self.__notify_observer__(obs, method,<EOL>self, prop_name, info)<EOL><DEDENT><DEDENT><DEDENT>
|
Send a notification to all registered observers.
*old* the value before the change occured.
|
f2884:c0:m17
|
def notify_method_before_change(self, prop_name, instance, meth_name,<EOL>args, kwargs):
|
assert prop_name in self.__instance_notif_before<EOL>for method, kw in self.__instance_notif_before[prop_name]:<EOL><INDENT>obs = method.__self__<EOL>if kw is None: <EOL><INDENT>self.__notify_observer__(obs, method,<EOL>self, instance,<EOL>meth_name, args, kwargs)<EOL><DEDENT>elif '<STR_LIT>' in kw: <EOL><INDENT>self.__notify_observer__(obs, method,<EOL>self, prop_name, instance,<EOL>meth_name, args, kwargs)<EOL><DEDENT>else:<EOL><INDENT>info = NTInfo('<STR_LIT>',<EOL>kw,<EOL>model=self, prop_name=prop_name,<EOL>instance=instance, method_name=meth_name,<EOL>args=args, kwargs=kwargs)<EOL>self.__notify_observer__(obs, method,<EOL>self, prop_name, info)<EOL><DEDENT><DEDENT>
|
Send a notification to all registered observers.
*instance* the object stored in the property.
*meth_name* name of the method we are about to call on *instance*.
|
f2884:c0:m18
|
def notify_method_after_change(self, prop_name, instance, meth_name,<EOL>res, args, kwargs):
|
assert prop_name in self.__instance_notif_after<EOL>for method, kw in self.__instance_notif_after[prop_name]:<EOL><INDENT>obs = method.__self__<EOL>if kw is None: <EOL><INDENT>self.__notify_observer__(obs, method,<EOL>self, instance,<EOL>meth_name, res, args, kwargs)<EOL><DEDENT>elif '<STR_LIT>' in kw: <EOL><INDENT>self.__notify_observer__(obs, method,<EOL>self, prop_name, instance,<EOL>meth_name, res, args, kwargs)<EOL><DEDENT>else:<EOL><INDENT>info = NTInfo('<STR_LIT>',<EOL>kw,<EOL>model=self, prop_name=prop_name,<EOL>instance=instance, method_name=meth_name,<EOL>result=res, args=args, kwargs=kwargs)<EOL>self.__notify_observer__(obs, method,<EOL>self, prop_name, info)<EOL><DEDENT><DEDENT>
|
Send a notification to all registered observers.
*args* the arguments we just passed to *meth_name*.
*res* the return value of the method call.
|
f2884:c0:m19
|
def notify_signal_emit(self, prop_name, arg):
|
assert prop_name in self.__signal_notif<EOL>for method, kw in self.__signal_notif[prop_name]:<EOL><INDENT>obs = method.__self__<EOL>if kw is None: <EOL><INDENT>self.__notify_observer__(obs, method,<EOL>self, arg)<EOL><DEDENT>elif '<STR_LIT>' in kw: <EOL><INDENT>self.__notify_observer__(obs, method,<EOL>self, prop_name, arg)<EOL><DEDENT>else:<EOL><INDENT>info = NTInfo('<STR_LIT>',<EOL>kw,<EOL>model=self, prop_name=prop_name, arg=arg)<EOL>self.__notify_observer__(obs, method,<EOL>self, prop_name, info)<EOL><DEDENT><DEDENT>
|
Emit a signal to all registered observers.
*prop_name* the property storing the :class:`~gtkmvc3.observable.Signal`
instance.
*arg* one arbitrary argument passed to observing methods.
|
f2884:c0:m20
|
def __get_prop_value(self, name):
|
return getattr(self, "<STR_LIT>" % name, None)<EOL>
|
Returns the property value, given its name.
|
f2884:c0:m21
|
@decorators.good_decorator<EOL>def observed(func):
|
def wrapper(*args, **kwargs):<EOL><INDENT>self = args[<NUM_LIT:0>]<EOL>assert(isinstance(self, Observable))<EOL>self._notify_method_before(self, func.__name__, args, kwargs)<EOL>res = func(*args, **kwargs)<EOL>self._notify_method_after(self, func.__name__, res, args, kwargs)<EOL>return res<EOL><DEDENT>log.logger.warning("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return wrapper<EOL>
|
Just like :meth:`Observable.observed`.
.. deprecated:: 1.99.1
|
f2885:m0
|
@classmethod<EOL><INDENT>@decorators.good_classmethod_decorator<EOL>def observed(cls, _func):<DEDENT>
|
def wrapper(*args, **kwargs):<EOL><INDENT>self = args[<NUM_LIT:0>]<EOL>assert(isinstance(self, Observable))<EOL>self._notify_method_before(self, _func.__name__, args, kwargs)<EOL>res = _func(*args, **kwargs)<EOL>self._notify_method_after(self, _func.__name__, res, args, kwargs)<EOL>return res<EOL><DEDENT>return wrapper<EOL>
|
Decorate methods to be observable. If they are called on an instance
stored in a property, the model will emit before and after
notifications.
|
f2885:c0:m0
|
def emit(self, arg=None):
|
for model,name in self.__get_models__():<EOL><INDENT>model.notify_signal_emit(name, arg)<EOL><DEDENT>
|
Emits the signal, passing the optional argument
|
f2885:c1:m1
|
def __notify_observer__(self, observer, method, *args, **kwargs):
|
assert observer in self.__observer_threads<EOL>if _threading.currentThread() == self.__observer_threads[observer]:<EOL><INDENT>return Model.__notify_observer__(self, observer, method,<EOL>*args, **kwargs)<EOL><DEDENT>GLib.idle_add(self.__idle_callback, observer, method, args, kwargs)<EOL>
|
This makes a call either through the gtk.idle list or a
direct method call depending whether the caller's thread is
different from the observer's thread
|
f2886:c0:m3
|
def add_adapter(widget_class, signal_name, getter, setter, value_type,<EOL>flavour=None):
|
new_tu = (widget_class, signal_name, getter, setter,<EOL>value_type, flavour)<EOL>for it,tu in enumerate(__def_adapter):<EOL><INDENT>if issubclass(tu[WIDGET], widget_class):<EOL><INDENT>__def_adapter.insert(it, new_tu)<EOL>return<EOL><DEDENT><DEDENT>__def_adapter.append(new_tu)<EOL>
|
This function can be used to extend at runtime the set of
default adapters. If given widget class which is being added is
already in the default set, it will be substituted by the new one
until the next removal (see remove_adapter).
@param flavour can be used to differentiate otherwise identical
entries (None for no flavour).
|
f2887:m4
|
def remove_adapter(widget_class, flavour=None):
|
for it,tu in enumerate(__def_adapter):<EOL><INDENT>if (widget_class == tu[WIDGET] and flavour == tu[FLAVOUR]):<EOL><INDENT>del __def_adapter[it]<EOL>return True<EOL><DEDENT><DEDENT>return False<EOL>
|
Removes the given widget class information from the default set
of adapters.
If widget_class had been previously added by using add_adapter,
the added adapter will be removed, restoring possibly previusly
existing adapter(s). Notice that this function will remove only
*one* adapter about given wiget_class (the first found in order),
even if many are currently stored.
@param flavour has to be used when the entry was added with a
particular flavour.
Returns True if one adapter was removed, False if no adapter was
removed.
|
f2887:m5
|
def search_adapter_info(wid, flavour=None):
|
t = (type(wid), flavour)<EOL>if t in __memoize__:<EOL><INDENT>return __memoize__[t]<EOL><DEDENT>for w in __def_adapter:<EOL><INDENT>if (isinstance(wid, w[WIDGET]) and flavour == w[FLAVOUR]):<EOL><INDENT>__memoize__[t] = w<EOL>return w<EOL><DEDENT><DEDENT>raise TypeError("<STR_LIT>" + str(t) + "<STR_LIT>")<EOL>
|
Given a widget returns the default tuple found in __def_adapter.
@param flavour can be used to specialize the search for a
particular tuple.
|
f2887:m6
|
def __init__(self, model, path, adapter):
|
self.model = model<EOL>self.prop_name = path[<NUM_LIT:0>]<EOL>self.path = path[<NUM_LIT:1>:]<EOL>self.adapter = adapter<EOL>self.next = None<EOL>Observer.__init__(self)<EOL>self.observe(self.update_widget, self.prop_name, assign=True)<EOL>self.observe_model(model)<EOL>self.create_next()<EOL>
|
*model* is an instance.
*path* is a list of strings, with the first naming a property of
*model*. Its value must have a property named like the second string,
and so on.
*adapter* is an instance. Its widget will be updated every time a
property in *path* changes. Currently this only covers assignment.
|
f2888:c0:m0
|
def __init__(self, model, prop_name,<EOL>prop_read=None, prop_write=None,<EOL>value_error=None,<EOL>spurious=False, prop_cast=True):
|
<EOL>Observer.__init__(self, spurious=spurious)<EOL>self._prop_name = prop_name<EOL>self._prop_cast = prop_cast<EOL>self._prop_read = prop_read<EOL>self._prop_write = prop_write<EOL>self._value_error = value_error<EOL>self._wid = None<EOL>self._wid_info = {}<EOL>self._itsme = False<EOL>self._connect_model(model)<EOL>
|
Observe one property of one model instance for assignment (and nothing
else). After you :meth:`connect_widget` those changes will be
propagated to that widget, and vice versa.
*prop_name* is a string. It may contain dots and will be resolved
using Python attribute access on *model*. All objects traversed must
be :class:`Model` instances.
The last part of the string names a property. Examples::
>>> "age"
observe("age")
observe_model(model)
>>> "child.age"
observe("age")
observe_model(model.child)
.. versionchanged:: 1.99.2
Changes to intermediate models used to be ignored.
*spurious* see superclass.
*prop_read* is an optional callable. It will be passed the actual
value of the model property and must return it in a format suitable
for the widget.
*prop_write* is the mirror image of *prop_read*.
*prop_cast* denotes whether to attempt a cast of the widget value to
the type of the previous property value, before passing the result to
*prop_write*. You cannot disable this unless you define *prop_write*.
*value_error* is an optional callable. It is used when the automatic
cast or *prop_write* raise :exc:`ValueError`. It will be passed this
adapter, the name of the property we observe (i.e. the last part of
*prop_name*) and the value obtained from the widget.
|
f2888:c1:m0
|
def get_property_name(self):
|
return self._prop_name<EOL>
|
Returns the name of the property we observe.
|
f2888:c1:m1
|
def get_widget(self):
|
return self._wid<EOL>
|
Returns the widget we are connected to, or None.
|
f2888:c1:m2
|
def connect_widget(self, wid,<EOL>getter=None, setter=None,<EOL>signal=None, arg=None, update=True,<EOL>flavour=None):
|
if wid in self._wid_info:<EOL><INDENT>raise ValueError("<STR_LIT>" + str(wid) + "<STR_LIT>")<EOL><DEDENT>wid_type = None<EOL>if None in (getter, setter, signal):<EOL><INDENT>w = search_adapter_info(wid, flavour)<EOL>if getter is None:<EOL><INDENT>getter = w[GETTER]<EOL><DEDENT>if setter is None:<EOL><INDENT>setter = w[SETTER]<EOL>wid_type = w[WIDTYPE]<EOL><DEDENT>if signal is None:<EOL><INDENT>signal = w[SIGNAL]<EOL><DEDENT><DEDENT>self._wid_info[wid] = (getter, setter, wid_type)<EOL>if signal:<EOL><INDENT>if arg:<EOL><INDENT>wid.connect(signal, self._on_wid_changed, arg)<EOL><DEDENT>else:<EOL><INDENT>wid.connect(signal, self._on_wid_changed)<EOL><DEDENT><DEDENT>self._wid = wid<EOL>if update:<EOL><INDENT>self.update_widget()<EOL><DEDENT>
|
Finish set-up by connecting the widget. The model was already
specified in the constructor.
*wid* is a widget instance.
*getter* is a callable. It is passed *wid* and must return its
current value.
*setter* is a callable. It is passed *wid* and the current value of
the model property and must update the widget.
*signal* is a string naming the signal to connect to on *wid*. When
it is emitted we update the model.
*getter*, *setter* and *signal* are optional. Missing values are
guessed from *wid* using
:meth:`gtkmvc3.adapters.default.search_adapter_info`. If nothing is
found this raises :exc:`TypeError`.
*arg* is an optional value passed to the handler for *signal*. This
doesn't do anything unless a subclass overrides the handler.
*update* denotes whether to update the widget from the model
immediately. Otherwise the widget stays unchanged until the first
notification.
*flavour* can be used to select special behaviours about
the adaptation when twice or more possibilities are
possibly handled for the same widget type. See
adapters.default for further information.
|
f2888:c1:m3
|
def update_model(self):
|
try: val = self._read_widget()<EOL>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self._write_property(val)<EOL><DEDENT>
|
Update the model with the current value from the widget.
It shouldn't ever be necessary to call this, if you connected to
the right signal.
|
f2888:c1:m4
|
def update_widget(self):
|
self._write_widget(self._read_property())<EOL>
|
Update the widget with the current value from the model.
Use this for changes to the property that assignment observation
doesn't catch.
|
f2888:c1:m5
|
def _connect_model(self, model):
|
parts = self._prop_name.split("<STR_LIT:.>")<EOL>if len(parts) > <NUM_LIT:1>:<EOL><INDENT>models = parts[:-<NUM_LIT:1>]<EOL>Intermediate(model, models, self)<EOL>for name in models:<EOL><INDENT>model = getattr(model, name)<EOL>if not isinstance(model, Model):<EOL><INDENT>raise TypeError("<STR_LIT>" + name +<EOL>"<STR_LIT>" +<EOL>str(model))<EOL><DEDENT><DEDENT>prop = parts[-<NUM_LIT:1>]<EOL><DEDENT>else: prop = parts[<NUM_LIT:0>]<EOL>if not hasattr(model, prop):<EOL><INDENT>raise ValueError("<STR_LIT>" + prop +<EOL>"<STR_LIT>" + str(model))<EOL><DEDENT>if model.has_property(prop):<EOL><INDENT>meth = types.MethodType(self._get_observer_fun(prop), self)<EOL>setattr(self, meth.__name__, meth)<EOL><DEDENT>self._prop = getattr(model, prop)<EOL>self._prop_name = prop<EOL>self._model = model<EOL>self.observe_model(model)<EOL>
|
Used internally to connect the property into the model, and
register self as a value observer for that property
|
f2888:c1:m6
|
def _get_observer_fun(self, prop_name):
|
def _observer_fun(self, model, old, new):<EOL><INDENT>if self._itsme:<EOL><INDENT>return<EOL><DEDENT>self._on_prop_changed()<EOL><DEDENT>_observer_fun.__name__ = "<STR_LIT>" % prop_name<EOL>return _observer_fun<EOL>
|
This is the code for an value change observer
|
f2888:c1:m7
|
def _get_property(self):
|
return getattr(self._model, self._prop_name)<EOL>
|
Private method that returns the value currently stored
into the property
|
f2888:c1:m8
|
def _set_property(self, val):
|
return setattr(self._model, self._prop_name, val)<EOL>
|
Private method that sets the value currently of the property.
|
f2888:c1:m9
|
def _read_property(self, *args):
|
if self._prop_read:<EOL><INDENT>return self._prop_read(self._get_property(*args))<EOL><DEDENT>return self._get_property(*args)<EOL>
|
Return the model's current value, using *prop_read* if used in the
constructor.
*args* is just passed on to :meth:`_get_property`. This does nothing,
but may be used in subclasses.
|
f2888:c1:m10
|
def _write_property(self, val, *args):
|
val_wid = val<EOL>try:<EOL><INDENT>totype = type(self._get_property(*args))<EOL>if (totype is not type(None) and<EOL>(self._prop_cast or not self._prop_write)):<EOL><INDENT>val = self._cast_value(val, totype)<EOL><DEDENT>if self._prop_write:<EOL><INDENT>val = self._prop_write(val)<EOL><DEDENT>self._itsme = True<EOL>self._set_property(val, *args)<EOL><DEDENT>except ValueError:<EOL><INDENT>self._itsme = False<EOL>if self._value_error:<EOL><INDENT>self._value_error(self, self._prop_name, val_wid)<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>except:<EOL><INDENT>self._itsme = False<EOL>raise<EOL><DEDENT>self._itsme = False<EOL>
|
Sets the value of property. Given val is transformed
accodingly to prop_write function when specified at
construction-time. A try to cast the value to the property
type is given.
|
f2888:c1:m11
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.