Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Start using flake8 and black and enforce in pre-commit hook #44

Merged
merged 3 commits into from
Sep 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
repos:
- repo: https://github.com/psf/black
rev: 21.8b0
hooks:
- id: black
language_version: python3.8
- repo: https://gitlab.com/pycqa/flake8
rev: 3.9.2
hooks:
- id: flake8
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ For a development installation (requires npm),

$ git clone https://github.com/mariobuikhuizen/ipyvue.git
$ cd ipyvue
$ pip install -e .
$ pip install -e ".[dev]"
$ jupyter nbextension install --py --symlink --sys-prefix ipyvue
$ jupyter nbextension enable --py --sys-prefix ipyvue
$ jupyter labextension develop . --overwrite
4 changes: 2 additions & 2 deletions ipyvue/ForceLoad.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@


class ForceLoad(DOMWidget):
_model_name = Unicode('ForceLoadModel').tag(sync=True)
_model_module = Unicode('jupyter-vue').tag(sync=True)
_model_name = Unicode("ForceLoadModel").tag(sync=True)
_model_module = Unicode("jupyter-vue").tag(sync=True)
_model_module_version = Unicode(semver).tag(sync=True)


Expand Down
4 changes: 2 additions & 2 deletions ipyvue/Html.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

class Html(VueWidget):

_model_name = Unicode('HtmlModel').tag(sync=True)
_model_name = Unicode("HtmlModel").tag(sync=True)

tag = Unicode().tag(sync=True)


__all__ = ['Html']
__all__ = ["Html"]
15 changes: 8 additions & 7 deletions ipyvue/Template.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,25 @@
template_registry = {}


def watch(path=''):
def watch(path=""):
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

log = logging.getLogger('ipyvue')
log = logging.getLogger("ipyvue")

class VueEventHandler(FileSystemEventHandler):
def on_modified(self, event):
super(VueEventHandler, self).on_modified(event)
if not event.is_directory:
if event.src_path in template_registry:
log.info(f'updating: {event.src_path}')
log.info(f"updating: {event.src_path}")
with open(event.src_path) as f:
template_registry[event.src_path].template = f.read()

observer = Observer()
path = os.path.normpath(path)
log.info(f'watching {path}')
log.info(f"watching {path}")
observer.schedule(VueEventHandler(), path, recursive=True)
observer.start()

Expand All @@ -41,11 +42,11 @@ def get_template(abs_path):


class Template(Widget):
_model_name = Unicode('TemplateModel').tag(sync=True)
_model_module = Unicode('jupyter-vue').tag(sync=True)
_model_name = Unicode("TemplateModel").tag(sync=True)
_model_module = Unicode("jupyter-vue").tag(sync=True)
_model_module_version = Unicode(semver).tag(sync=True)

template = Unicode(None, allow_none=True).tag(sync=True)


__all__ = ['Template', 'watch']
__all__ = ["Template", "watch"]
10 changes: 7 additions & 3 deletions ipyvue/VueComponentRegistry.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@


class VueComponent(DOMWidget):
_model_name = Unicode('VueComponentModel').tag(sync=True)
_model_module = Unicode('jupyter-vue').tag(sync=True)
_model_name = Unicode("VueComponentModel").tag(sync=True)
_model_module = Unicode("jupyter-vue").tag(sync=True)
_model_module_version = Unicode(semver).tag(sync=True)

name = Unicode().tag(sync=True)
Expand All @@ -31,4 +31,8 @@ def register_component_from_file(self, name, file_name):
register_component_from_string(name, f.read())


__all__ = ['VueComponent', 'register_component_from_string', 'register_component_from_file']
__all__ = [
"VueComponent",
"register_component_from_string",
"register_component_from_file",
]
104 changes: 56 additions & 48 deletions ipyvue/VueTemplateWidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
import inspect
from importlib import import_module

OBJECT_REF = 'objectRef'
FUNCTION_REF = 'functionRef'
OBJECT_REF = "objectRef"
FUNCTION_REF = "functionRef"


class Events(object):
Expand All @@ -23,94 +23,98 @@ def resolve_ref(value):
if isinstance(value, dict):
if OBJECT_REF in value.keys():
obj = getattr(self, value[OBJECT_REF])
for path_item in value.get('path', []):
for path_item in value.get("path", []):
obj = obj[path_item]
return obj
if FUNCTION_REF in value.keys():
fn = getattr(self, value[FUNCTION_REF])
args = value.get('args', [])
kwargs = value.get('kwargs', {})
args = value.get("args", [])
kwargs = value.get("kwargs", {})
return fn(*args, **kwargs)
return value

if 'create_widget' in content.keys():
module_name = content['create_widget'][0]
class_name = content['create_widget'][1]
props = {k: resolve_ref(v) for k, v in content['props'].items()}
if "create_widget" in content.keys():
module_name = content["create_widget"][0]
class_name = content["create_widget"][1]
props = {k: resolve_ref(v) for k, v in content["props"].items()}
module = import_module(module_name)
widget = getattr(module, class_name)(**props, model_id=content['id'])
widget = getattr(module, class_name)(**props, model_id=content["id"])
self._component_instances = [*self._component_instances, widget]
elif 'update_ref' in content.keys():
widget = DOMWidget.widgets[content['id']]
prop = content['prop']
obj = resolve_ref(content['update_ref'])
elif "update_ref" in content.keys():
widget = DOMWidget.widgets[content["id"]]
prop = content["prop"]
obj = resolve_ref(content["update_ref"])
setattr(widget, prop, obj)
elif 'destroy_widget' in content.keys():
self._component_instances = [w for w in self._component_instances
if w.model_id != content['destroy_widget']]
elif 'event' in content.keys():
elif "destroy_widget" in content.keys():
self._component_instances = [
w
for w in self._component_instances
if w.model_id != content["destroy_widget"]
]
elif "event" in content.keys():
event = content.get("event", "")
data = content.get("data", {})
if buffers:
getattr(self, 'vue_' + event)(data, buffers)
getattr(self, "vue_" + event)(data, buffers)
else:
getattr(self, 'vue_' + event)(data)
getattr(self, "vue_" + event)(data)


def _value_to_json(x, obj):
if inspect.isclass(x):
return {
'class': [x.__module__, x.__name__],
'props': x.class_trait_names()
}
return widget_serialization['to_json'](x, obj)
return {"class": [x.__module__, x.__name__], "props": x.class_trait_names()}
return widget_serialization["to_json"](x, obj)


def _class_to_json(x, obj):
if not x:
return widget_serialization['to_json'](x, obj)
return widget_serialization["to_json"](x, obj)
return {k: _value_to_json(v, obj) for k, v in x.items()}


def as_refs(name, data):
def to_ref_structure(obj, path):
if isinstance(obj, list):
return [to_ref_structure(item, [*path, index]) for index, item in enumerate(obj)]
return [
to_ref_structure(item, [*path, index]) for index, item in enumerate(obj)
]
if isinstance(obj, dict):
return {k: to_ref_structure(v, [*path, k]) for k, v in obj.items()}

# add object id to detect a new object in the same structure
return {OBJECT_REF: name, 'path': path, 'id': id(obj)}
return {OBJECT_REF: name, "path": path, "id": id(obj)}

return to_ref_structure(data, [])


class VueTemplate(DOMWidget, Events):

class_component_serialization = {
'from_json': widget_serialization['to_json'],
'to_json': _class_to_json
"from_json": widget_serialization["to_json"],
"to_json": _class_to_json,
}

# Force the loading of jupyter-vue before dependent extensions when in a static context (embed,
# voila)
_jupyter_vue = Any(force_load_instance, read_only=True).tag(sync=True, **widget_serialization)
# Force the loading of jupyter-vue before dependent extensions when in a static
# context (embed, voila)
_jupyter_vue = Any(force_load_instance, read_only=True).tag(
sync=True, **widget_serialization
)

_model_name = Unicode('VueTemplateModel').tag(sync=True)
_model_name = Unicode("VueTemplateModel").tag(sync=True)

_view_name = Unicode('VueView').tag(sync=True)
_view_name = Unicode("VueView").tag(sync=True)

_view_module = Unicode('jupyter-vue').tag(sync=True)
_view_module = Unicode("jupyter-vue").tag(sync=True)

_model_module = Unicode('jupyter-vue').tag(sync=True)
_model_module = Unicode("jupyter-vue").tag(sync=True)

_view_module_version = Unicode(semver).tag(sync=True)

_model_module_version = Unicode(semver).tag(sync=True)

template = Union([
Instance(Template),
Unicode()]).tag(sync=True, **widget_serialization)
template = Union([Instance(Template), Unicode()]).tag(
sync=True, **widget_serialization
)

css = Unicode(None, allow_none=True).tag(sync=True)

Expand All @@ -121,15 +125,16 @@ class VueTemplate(DOMWidget, Events):
events = List(Unicode(), allow_none=True).tag(sync=True)

components = Dict(default_value=None, allow_none=True).tag(
sync=True, **class_component_serialization)
sync=True, **class_component_serialization
)

_component_instances = List().tag(sync=True, **widget_serialization)

template_file = None

def __init__(self, *args, **kwargs):
if self.template_file:
abs_path = ''
abs_path = ""
if type(self.template_file) == str:
abs_path = os.path.abspath(self.template_file)
elif type(self.template_file) == tuple:
Expand All @@ -140,21 +145,24 @@ def __init__(self, *args, **kwargs):

super().__init__(*args, **kwargs)

sync_ref_traitlets = [v for k, v in self.traits().items()
if 'sync_ref' in v.metadata.keys()]
sync_ref_traitlets = [
v for k, v in self.traits().items() if "sync_ref" in v.metadata.keys()
]

def create_ref_and_observe(traitlet):
data = traitlet.get(self)
ref_name = traitlet.name + '_ref'
self.add_traits(**{ref_name: Any(as_refs(traitlet.name, data)).tag(sync=True)})
ref_name = traitlet.name + "_ref"
self.add_traits(
**{ref_name: Any(as_refs(traitlet.name, data)).tag(sync=True)}
)

def on_ref_source_change(change):
setattr(self, ref_name, as_refs(traitlet.name, change['new']))
setattr(self, ref_name, as_refs(traitlet.name, change["new"]))

self.observe(on_ref_source_change, traitlet.name)

for traitlet in sync_ref_traitlets:
create_ref_and_observe(traitlet)


__all__ = ['VueTemplate']
__all__ = ["VueTemplate"]
Loading