PKKLNnbparameterise/__init__.py"""Re-run a notebook substituting input parameters in the first cell.""" __version__ = '0.3' from .code import (Parameter, extract_parameters, replace_definitions, parameter_values, ) PKBLUeX  nbparameterise/code.pyimport copy import importlib import re from nbconvert.preprocessors import ExecutePreprocessor class Parameter(object): def __init__(self, name, vtype, value=None, metadata=None): self.name = name self.type = vtype self.value = value self.metadata = metadata or {} def __repr__(self): params = [repr(self.name), self.type.__name__] if self.value is not None: params.append("value=%r" % self.value) return "Parameter(%s)" % ", ".join(params) def with_value(self, value): """Returns a copy with value set to a new value.""" return type(self)(self.name, self.type, value, self.metadata or None) def first_code_cell(nb): for cell in nb.cells: if cell.cell_type == 'code': return cell kernel_name_re = re.compile(r'\w+$') def get_driver_module(nb, override=None): if override: module_name = override else: module_name = nb.metadata.get('language_info', {}).get('name', 'python') assert kernel_name_re.match(module_name) return importlib.import_module('nbparameterise.code_drivers.%s' % module_name) def extract_parameters(nb, lang=None): """Returns a list of Parameter instances derived from the notebook. This looks for assignments (like 'n = 50') in the first code cell of the notebook. The parameters may also have some metadata stored in the notebook metadata; this will be attached as the .metadata instance on each one. lang may be used to override the kernel name embedded in the notebook. For now, nbparameterise only handles 'python3' and 'python2'. """ drv = get_driver_module(nb, override=lang) params = list(drv.extract_definitions(first_code_cell(nb).source)) # Add extra info from notebook metadata for param in params: param.metadata = nb.metadata.get('parameterise', {}).get(param.name, {}) return params def parameter_values(params, **kwargs): """Return a copy of the parameter list, substituting values from kwargs. Usage example:: params = parameter_values(params, stock='GOOG', days_back=300 ) Any parameters not supplied will keep their original value. """ res = [] for p in params: if p.name in kwargs: res.append(p.with_value(kwargs[p.name])) else: res.append(p) return res def replace_definitions(nb, values, execute=True, execute_resources=None, lang=None): """Return a copy of nb with the first code cell defining the given parameters. values should be a list of Parameter objects (as returned by extract_parameters), with their .value attribute set to the desired value. If execute is True, the notebook is executed with the new values. execute_resources is passed to nbconvert.ExecutePreprocessor; it's a dict, and if possible should contain a 'path' key for the working directory in which to run the notebook. lang may be used to override the kernel name embedded in the notebook. For now, nbparameterise only handles 'python3' and 'python2'. """ nb = copy.deepcopy(nb) drv = get_driver_module(nb, override=lang) first_code_cell(nb).source = drv.build_definitions(values) if execute: resources = execute_resources or {} nb, resources = ExecutePreprocessor().preprocess(nb, resources) return nb PK\dH2'nbparameterise/code_drivers/__init__.py PK\dHڃp%nbparameterise/code_drivers/python.pyimport ast import astcheck import astsearch from ..code import Parameter __all__ = ['extract_definitions', 'build_definitions'] def check_fillable_node(node, path): if isinstance(node, (ast.Num, ast.Str)): return elif isinstance(node, ast.NameConstant) and (node.value in (True, False)): return raise astcheck.ASTMismatch(path, node, 'number, string or boolean') definition_pattern = ast.Assign(targets=[ast.Name()], value=check_fillable_node) def type_and_value(node): if isinstance(node, ast.Num): # int or float return type(node.n), node.n elif isinstance(node, ast.Str): return str, node.s return (bool, node.value) def extract_definitions(cell): cell_ast = ast.parse(cell) for assign in astsearch.ASTPatternFinder(definition_pattern).scan_ast(cell_ast): yield Parameter(assign.targets[0].id, *type_and_value(assign.value)) def build_definitions(inputs): return "\n".join("{0.name} = {0.value!r}".format(i) for i in inputs)PK\dHm 599$nbparameterise-0.3.dist-info/LICENSEThe MIT License (MIT) Copyright (c) 2016 Thomas Kluyver Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HNO"nbparameterise-0.3.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,zd&Y)r$[)T&UrPK!Hjnx%nbparameterise-0.3.dist-info/METADATA}U_o68IKΚbRkkcO%,T}ݑ8 $0}^oN-fNZ*bH/Ūo[i bb{ +{t{8_#T:6M*nLI'Ts|U0]h'x>KwO巅x ֵiOڸ`+UQq>m̙;E|(L߈ :OF{>Y q霪Rd,W]Y%o?OɌ8课<lDa4yZ4ؖ)ƃlzt)|Q`z[1r ZiJ&O3%f1mH Ll[RAvUL4 W1ŎvAh!>\,lrp\_/.X<j%-,]Y5s&L$F!O;$^;?\w$SE-(DK_@ P iٔ(iJ0ВrY!(ێsΙv}JVw+ijT+WMIGr\26<T)WVwBvVJc.. [A1En(#߬o?lB^^h~)ͶM^*Gܜ2`-_6DYg1@u)c͖b Mi?h$;{5{;[}s,Mn܄qU!mNد!ëX=`:/VaG-S :uiPS<}!.\kG}L>0VmSu>/ВGb’>?5/ry}6U\EԻ%FѸ9߅my;m>>׊md[R'6F<ć;]0LpX3Z?МnxIZbd64rZxd<&uZbt5nG3ډ,%ܛnO]# .Lwڶ-۫VI~ļ?A7=ʨ1M+"$QT]Իݔ+\WNKd]ZOn(e}U.s_ǶRv p@c=PKKLNnbparameterise/__init__.pyPKBLUeX  nbparameterise/code.pyPK\dH2'nbparameterise/code_drivers/__init__.pyPK\dHڃp%nbparameterise/code_drivers/python.pyPK\dHm 599$Tnbparameterise-0.3.dist-info/LICENSEPK!HNO"nbparameterise-0.3.dist-info/WHEELPK!Hjnx%]nbparameterise-0.3.dist-info/METADATAPK!HYde#Cnbparameterise-0.3.dist-info/RECORDPKz