coconut-develop 3.2.0.post0.dev15__py2.py3-none-any.whl → 3.2.0.post0.dev17__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
__coconut__/__init__.pyi CHANGED
@@ -3,7 +3,7 @@
3
3
  # -----------------------------------------------------------------------------------------------------------------------
4
4
 
5
5
  """
6
- Author: Evan Hubinger
6
+ Authors: Evan Hubinger, Claude
7
7
  License: Apache 2.0
8
8
  Description: MyPy stub file for __coconut__.py.
9
9
  """
@@ -1439,7 +1439,7 @@ class multiset(_t.Generic[_T], _coconut.collections.Counter[_T]):
1439
1439
  def discard(self, item: _T) -> None: ...
1440
1440
  def remove(self, item: _T) -> None: ...
1441
1441
  def isdisjoint(self, other: _coconut.collections.Counter[_T]) -> bool: ...
1442
- def __xor__(self, other: _coconut.collections.Counter[_T]) -> multiset[_T]: ...
1442
+ def __xor__(self, other: _coconut.collections.Counter[_U]) -> multiset[_T | _U]: ...
1443
1443
  def count(self, item: _T) -> int: ...
1444
1444
  def __fmap__(self, func: _t.Callable[[_T], _U]) -> multiset[_U]: ...
1445
1445
  _coconut_multiset = multiset
coconut/_pyparsing.py CHANGED
@@ -6,7 +6,7 @@
6
6
  # -----------------------------------------------------------------------------------------------------------------------
7
7
 
8
8
  """
9
- Author: Evan Hubinger
9
+ Authors: Evan Hubinger, Claude
10
10
  License: Apache 2.0
11
11
  Description: Wrapper around PyParsing that selects the best available implementation.
12
12
  """
@@ -248,7 +248,7 @@ USE_COMPUTATION_GRAPH = get_bool_env_var(
248
248
  # it breaks some features and balloons the memory footprint
249
249
  # and not PYPY
250
250
  ),
251
- )
251
+ ) # type: bool
252
252
 
253
253
  SUPPORTS_ADAPTIVE = (
254
254
  USE_COMPUTATION_GRAPH
coconut/api.py CHANGED
@@ -53,10 +53,10 @@ from coconut.constants import (
53
53
  GLOBAL_STATE = None
54
54
 
55
55
 
56
- def get_state(state=None):
57
- """Get a Coconut state object; None gets a new state, False gets the global state."""
56
+ def get_state(state=True):
57
+ """Get a Coconut state object; True gets a new state, False gets the global state."""
58
58
  global GLOBAL_STATE
59
- if state is None:
59
+ if state is None or state is True:
60
60
  return Command()
61
61
  elif state is False:
62
62
  if GLOBAL_STATE is None:
coconut/api.pyi CHANGED
@@ -38,7 +38,7 @@ class CoconutException(Exception):
38
38
  GLOBAL_STATE: Optional[Command] = None
39
39
 
40
40
 
41
- def get_state(state: Optional[Command] = None) -> Command:
41
+ def get_state(state: Optional[Command] | bool = None) -> Command:
42
42
  """Get a Coconut state object; None gets a new state, False gets the global state."""
43
43
  ...
44
44
 
@@ -46,7 +46,7 @@ def get_state(state: Optional[Command] = None) -> Command:
46
46
  def cmd(
47
47
  args: Text | bytes | Iterable,
48
48
  *,
49
- state: Command | None = ...,
49
+ state: Optional[Command] | bool = ...,
50
50
  argv: Iterable[Text] | None = None,
51
51
  interact: bool = False,
52
52
  default_target: Text | None = None,
@@ -81,7 +81,7 @@ def setup(
81
81
  no_tco: bool = False,
82
82
  no_wrap: bool = False,
83
83
  pure: bool = False,
84
- state: Optional[Command] = ...,
84
+ state: Optional[Command] | bool = ...,
85
85
  ) -> None:
86
86
  """Set up the given state object."""
87
87
  ...
@@ -91,7 +91,7 @@ def warm_up(
91
91
  streamline: bool = False,
92
92
  enable_incremental_mode: bool = False,
93
93
  *,
94
- state: Optional[Command] = ...,
94
+ state: Optional[Command] | bool = ...,
95
95
  ) -> None:
96
96
  """Warm up the given state object."""
97
97
  ...
@@ -103,7 +103,7 @@ PARSERS: Dict[Text, Callable] = ...
103
103
  def parse(
104
104
  code: Text,
105
105
  mode: Text = ...,
106
- state: Optional[Command] = ...,
106
+ state: Optional[Command] | bool = ...,
107
107
  keep_internal_state: Optional[bool] = None,
108
108
  ) -> Text:
109
109
  """Compile Coconut code."""
@@ -114,7 +114,7 @@ def coconut_exec(
114
114
  expression: Text,
115
115
  globals: Optional[Dict[Text, Any]] = None,
116
116
  locals: Optional[Dict[Text, Any]] = None,
117
- state: Optional[Command] = ...,
117
+ state: Optional[Command] | bool = ...,
118
118
  keep_internal_state: Optional[bool] = None,
119
119
  ) -> None:
120
120
  """Compile and evaluate Coconut code."""
@@ -125,7 +125,7 @@ def coconut_eval(
125
125
  expression: Text,
126
126
  globals: Optional[Dict[Text, Any]] = None,
127
127
  locals: Optional[Dict[Text, Any]] = None,
128
- state: Optional[Command] = ...,
128
+ state: Optional[Command] | bool = ...,
129
129
  keep_internal_state: Optional[bool] = None,
130
130
  ) -> Any:
131
131
  """Compile and evaluate Coconut code."""
@@ -6,7 +6,7 @@
6
6
  # -----------------------------------------------------------------------------------------------------------------------
7
7
 
8
8
  """
9
- Authors: Evan Hubinger, Fred Buchanan, Noah Lipsyc, Ishaan Verma
9
+ Authors: Evan Hubinger, Fred Buchanan, Noah Lipsyc, Ishaan Verma, Claude
10
10
  License: Apache 2.0
11
11
  Description: The Coconut command-line utility.
12
12
  """
@@ -54,6 +54,7 @@ from coconut.constants import (
54
54
  icoconut_default_kernel_names,
55
55
  icoconut_default_kernel_dirs,
56
56
  icoconut_custom_kernel_name,
57
+ icoconut_custom_kernel_dir,
57
58
  icoconut_old_kernel_names,
58
59
  exit_chars,
59
60
  verbose_mypy_args,
@@ -396,7 +397,7 @@ class Command(object):
396
397
  elif getattr(args, "and"):
397
398
  raise CoconutException("--and should only be used for extra source/dest pairs, not the first source/dest pair")
398
399
  elif (
399
- args.run
400
+ (args.run and not args.interact)
400
401
  or args.no_write
401
402
  or args.force
402
403
  or args.package
@@ -1116,10 +1117,14 @@ class Command(object):
1116
1117
  install_args = args if just_install else []
1117
1118
 
1118
1119
  # always update the custom kernel, but only reinstall it if it isn't already there or just installing
1119
- custom_kernel_dir = install_custom_kernel(logger=logger)
1120
- if custom_kernel_dir is not None and (icoconut_custom_kernel_name not in kernel_list or just_install):
1120
+ custom_kernel_installed = install_custom_kernel(logger=logger) is not None
1121
+ if custom_kernel_installed and (icoconut_custom_kernel_name not in kernel_list or just_install):
1121
1122
  logger.show_sig("Installing Jupyter kernel {name!r}...".format(name=icoconut_custom_kernel_name))
1122
- if self.install_jupyter_kernel(jupyter, custom_kernel_dir, install_args):
1123
+ # we install from icoconut_custom_kernel_dir rather than the directory returned by
1124
+ # install_custom_kernel since the latter might be the same as the destination
1125
+ # jupyter installs to (e.g. when sys.exec_prefix is /usr/local), in which case
1126
+ # jupyter would delete the kernel before copying it
1127
+ if self.install_jupyter_kernel(jupyter, icoconut_custom_kernel_dir, install_args):
1123
1128
  newly_installed_kernels.append(icoconut_custom_kernel_name)
1124
1129
 
1125
1130
  if just_install:
@@ -6,7 +6,7 @@
6
6
  # -----------------------------------------------------------------------------------------------------------------------
7
7
 
8
8
  """
9
- Author: Evan Hubinger
9
+ Authors: Evan Hubinger, Claude
10
10
  License: Apache 2.0
11
11
  Description: Compiles Coconut code into Python code.
12
12
  """
@@ -635,20 +635,16 @@ class Compiler(Grammar, pickleable_obj):
635
635
  def get_empty_scope(self, inner=False):
636
636
  """Get an empty scope for the parsing_context."""
637
637
  parent = self.current_parsing_context("scope")
638
+ if parent is not None and parent["all_vars"] is None:
639
+ inner = True
638
640
  return {
639
641
  "final_vars": {},
640
642
  "pure_vars": {},
641
643
  "all_vars": None if inner else set(),
642
644
  "parent": parent,
645
+ "callbacks": [],
643
646
  }
644
647
 
645
- def init_parsing_context(self, inner=False):
646
- """Initialize parsing context."""
647
- self.parsing_context = defaultdict(list)
648
- # initialize module-level scopes
649
- self.parsing_context["scope"].append(self.get_empty_scope(inner=inner))
650
- return self.parsing_context
651
-
652
648
  def reset(self, keep_state=False, filename=None):
653
649
  """Reset references.
654
650
 
@@ -683,8 +679,7 @@ class Compiler(Grammar, pickleable_obj):
683
679
  self.shown_warnings = set()
684
680
  if not keep_state:
685
681
  self.computation_graph_caches = defaultdict(staledict)
686
- self.final_checks = []
687
- self.init_parsing_context()
682
+ self.parsing_context = defaultdict(list)
688
683
 
689
684
  @contextmanager
690
685
  def inner_environment(self, ln=None):
@@ -702,11 +697,13 @@ class Compiler(Grammar, pickleable_obj):
702
697
  num_lines, self.num_lines = self.num_lines, 0
703
698
  remaining_original, self.remaining_original = self.remaining_original, None
704
699
  shown_warnings, self.shown_warnings = self.shown_warnings, set()
705
- parsing_context = self.parsing_context
706
- self.init_parsing_context(inner=True)
700
+ parsing_context, self.parsing_context = self.parsing_context, defaultdict(list)
707
701
  try:
708
- with ComputationNode.using_overrides():
709
- yield
702
+ with self.add_to_parsing_context({
703
+ "scope": self.get_empty_scope(inner=True),
704
+ }):
705
+ with ComputationNode.using_overrides():
706
+ yield
710
707
  finally:
711
708
  self.outer_ln = outer_ln
712
709
  self.line_numbers = line_numbers
@@ -1525,8 +1522,8 @@ class Compiler(Grammar, pickleable_obj):
1525
1522
  """Acquire the lock and reset the parser."""
1526
1523
  filename = None if codepath is None else os.path.basename(codepath)
1527
1524
  with self.lock:
1528
- self.reset(keep_state, filename)
1529
1525
  Compiler.current_compiler = self
1526
+ self.reset(keep_state, filename)
1530
1527
  yield
1531
1528
 
1532
1529
  def streamline(self, grammars, inputstring=None, force=False, inner=False):
@@ -1557,8 +1554,6 @@ class Compiler(Grammar, pickleable_obj):
1557
1554
  if info["imported"] and not info["referenced"]:
1558
1555
  for loc in info["imported"]:
1559
1556
  self.strict_err_or_warn("found unused import " + repr(self.reformat(name, ignore_errors=True)), original, loc, noqa_able=True, endpoint=False)
1560
- for final_check in self.final_checks:
1561
- final_check()
1562
1557
 
1563
1558
  def pickle_cache(self, original, cache_path, include_incremental=True):
1564
1559
  """Pickle the pyparsing cache for original to cache_path."""
@@ -1838,11 +1833,15 @@ class Compiler(Grammar, pickleable_obj):
1838
1833
  with logger.gather_parsing_stats():
1839
1834
  try:
1840
1835
  pre_procd = self.pre(inputstring, keep_state=keep_state, **preargs)
1841
- if isinstance(parser, tuple):
1842
- init_parser, line_parser = parser
1843
- parsed = self.parse_line_by_line(init_parser, line_parser, pre_procd)
1844
- else:
1845
- parsed = parse(parser, pre_procd, inner=False)
1836
+ # handle module-level scope
1837
+ with self.add_to_parsing_context({
1838
+ "scope": self.get_empty_scope(inner=keep_state),
1839
+ }):
1840
+ if isinstance(parser, tuple):
1841
+ init_parser, line_parser = parser
1842
+ parsed = self.parse_line_by_line(init_parser, line_parser, pre_procd)
1843
+ else:
1844
+ parsed = parse(parser, pre_procd, inner=False)
1846
1845
  out = self.post(parsed, keep_state=keep_state, **postargs)
1847
1846
  except ParseBaseException as err:
1848
1847
  raise self.make_parse_err(err)
@@ -4093,7 +4092,7 @@ else:
4093
4092
  imp_name=imp_as if imp_as is not None else imp,
4094
4093
  imp_lookup=".".join([existing_imp] + module_path[1:] + ([imp] if imp_from is not None else [])),
4095
4094
  )
4096
- if lazy and self.target_info < (3, 15):
4095
+ if lazy == "emulated":
4097
4096
  out_lines = []
4098
4097
  fake_mods = (imp_from if imp_from is not None else imp).split(".")
4099
4098
  for i in range(1, len(fake_mods)):
@@ -4108,6 +4107,7 @@ else:
4108
4107
  ))
4109
4108
  return "\n".join(out_lines)
4110
4109
  else:
4110
+ internal_assert(not lazy or lazy == "native", "invalid lazy import type", lazy)
4111
4111
  return (
4112
4112
  ("lazy " if lazy else "")
4113
4113
  + ("from " + imp_from + " " if imp_from is not None else "")
@@ -4218,6 +4218,11 @@ else:
4218
4218
  )
4219
4219
  return "\n".join(stmts)
4220
4220
 
4221
+ def stmt_at_top_level(self, original, loc):
4222
+ """Determine whether the statement starting at loc is unindented."""
4223
+ line_start = original.rfind("\n", 0, loc) + 1
4224
+ return not original[line_start:loc].replace(closeindent, "")
4225
+
4221
4226
  def import_handle(self, original, loc, tokens):
4222
4227
  """Universalizes imports."""
4223
4228
  if len(tokens) == 2:
@@ -4229,7 +4234,15 @@ else:
4229
4234
  raise CoconutInternalException("invalid import tokens", tokens)
4230
4235
 
4231
4236
  internal_assert(lazy in ("lazy", ""), original, loc, "invalid import type token", lazy)
4232
- lazy = lazy == "lazy"
4237
+ if not lazy:
4238
+ lazy = None
4239
+ # native lazy imports are only allowed at the top level (not inside
4240
+ # functions, classes, or try/except blocks), so we only use them for
4241
+ # unindented statements and otherwise emulate them
4242
+ elif self.target_info >= (3, 15) and self.stmt_at_top_level(original, loc):
4243
+ lazy = "native"
4244
+ else:
4245
+ lazy = "emulated"
4233
4246
 
4234
4247
  if imp_from == "__future__":
4235
4248
  if lazy:
@@ -4643,11 +4656,12 @@ def {func_name}({iter_var}):
4643
4656
  def get_parent_expr_setnames(self):
4644
4657
  """Get all expr_setnames in parent contexts, but not the current context."""
4645
4658
  expr_setname_context = self.current_parsing_context("expr_setnames")
4646
- parent_context = expr_setname_context["parent"]
4647
4659
  parent_setnames = set()
4648
- while parent_context:
4649
- parent_setnames |= parent_context["new_names"]
4650
- parent_context = parent_context["parent"]
4660
+ if expr_setname_context is not None:
4661
+ parent_context = expr_setname_context["parent"]
4662
+ while parent_context:
4663
+ parent_setnames |= parent_context["new_names"]
4664
+ parent_context = parent_context["parent"]
4651
4665
  return parent_setnames
4652
4666
 
4653
4667
  def handle_expr_scope_closure(self, name, loc):
@@ -5303,7 +5317,7 @@ class {protocol_var}({tokens}, _coconut.typing.Protocol): pass
5303
5317
  return default
5304
5318
 
5305
5319
  @contextmanager
5306
- def add_to_parsing_context(self, name_obj_dict, callbacks_keys_dict=None):
5320
+ def add_to_parsing_context(self, name_obj_dict):
5307
5321
  """Put all the given objects on their respective parsing context stacks."""
5308
5322
  for name, obj in name_obj_dict.items():
5309
5323
  self.parsing_context[name].append(obj)
@@ -5312,11 +5326,9 @@ class {protocol_var}({tokens}, _coconut.typing.Protocol): pass
5312
5326
  finally:
5313
5327
  for name in name_obj_dict:
5314
5328
  popped_ctx = self.parsing_context[name].pop()
5315
- if callbacks_keys_dict is not None:
5316
- callbacks_key = callbacks_keys_dict.get(name)
5317
- if callbacks_key is not None:
5318
- for callback in popped_ctx[callbacks_key]:
5319
- callback()
5329
+ if "callbacks" in popped_ctx:
5330
+ for callback in popped_ctx["callbacks"]:
5331
+ callback()
5320
5332
 
5321
5333
  def funcname_typeparams_handle(self, tokens):
5322
5334
  """Handle function names with type parameters."""
@@ -5584,7 +5596,6 @@ class {protocol_var}({tokens}, _coconut.typing.Protocol): pass
5584
5596
  "callbacks": [],
5585
5597
  "loc": loc,
5586
5598
  }},
5587
- callbacks_keys_dict={"expr_setnames": "callbacks"},
5588
5599
  ):
5589
5600
  yield
5590
5601
 
@@ -5788,7 +5799,10 @@ class {protocol_var}({tokens}, _coconut.typing.Protocol): pass
5788
5799
  and name not in self.get_parent_expr_setnames()
5789
5800
  ))
5790
5801
  ):
5791
- self.final_checks.append(partial(self.check_undefined_name, original, loc, name, scope, self.outer_ln))
5802
+ parent_scope = scope
5803
+ while parent_scope["parent"] is not None:
5804
+ parent_scope = parent_scope["parent"]
5805
+ parent_scope["callbacks"].append(partial(self.check_undefined_name, original, loc, name, scope, self.outer_ln))
5792
5806
 
5793
5807
  # only mark as final after all checks pass
5794
5808
  if is_final:
@@ -6,7 +6,7 @@
6
6
  # -----------------------------------------------------------------------------------------------------------------------
7
7
 
8
8
  """
9
- Author: Evan Hubinger
9
+ Authors: Evan Hubinger, Claude
10
10
  License: Apache 2.0
11
11
  Description: Defines the Coconut grammar.
12
12
  """
@@ -27,6 +27,7 @@ from __future__ import print_function, absolute_import, unicode_literals, divisi
27
27
 
28
28
  from coconut.root import * # NOQA
29
29
 
30
+ import re
30
31
  from collections import defaultdict
31
32
  from contextlib import contextmanager
32
33
  from coconut.root import _coconut_partial as partial
@@ -63,6 +64,7 @@ from coconut.terminal import (
63
64
  internal_assert,
64
65
  )
65
66
  from coconut.constants import (
67
+ non_syntactic_newline,
66
68
  openindent,
67
69
  closeindent,
68
70
  strwrapper,
@@ -267,6 +269,19 @@ def add_bracks_handle(tokens):
267
269
  return "[" + item + "]"
268
270
 
269
271
 
272
+ collapse_non_syntactic_newlines_regex = re.compile(re.escape(non_syntactic_newline) + r"[ \t]*")
273
+
274
+
275
+ def collapse_non_syntactic_newlines_handle(tokens):
276
+ """Collapse line continuations in raw text into single spaces.
277
+
278
+ Raw text (e.g. xonsh shell commands) is passed through verbatim, so any line continuations in it,
279
+ which are represented by non_syntactic_newline, need to be collapsed, otherwise they'd be expanded
280
+ back out into (indented) separate lines without their original backslashes."""
281
+ item, = tokens
282
+ return collapse_non_syntactic_newlines_regex.sub(" ", item)
283
+
284
+
270
285
  def strip_parens_handle(tokens):
271
286
  """Strip parentheses."""
272
287
  item, = tokens
@@ -2768,16 +2783,22 @@ class Grammar(object):
2768
2783
  brackets = originalTextFor(nestedExpr("[", "]", ignoreExpr=None))
2769
2784
  braces = originalTextFor(nestedExpr("{", "}", ignoreExpr=None))
2770
2785
 
2771
- unsafe_anything_stmt = originalTextFor(regex_item("[^\n]+\n+"))
2772
- unsafe_xonsh_command = originalTextFor(
2773
- (Optional(at) + dollar | bang)
2774
- + ~(lparen + rparen | lbrack + rbrack | lbrace + rbrace)
2775
- + any_of(
2776
- parens,
2777
- brackets,
2778
- braces,
2779
- unsafe_name,
2780
- )
2786
+ unsafe_anything_stmt = attach(
2787
+ originalTextFor(regex_item("[^\n]+\n+")),
2788
+ collapse_non_syntactic_newlines_handle,
2789
+ )
2790
+ unsafe_xonsh_command = attach(
2791
+ originalTextFor(
2792
+ (Optional(at) + dollar | bang)
2793
+ + ~(lparen + rparen | lbrack + rbrack | lbrace + rbrace)
2794
+ + any_of(
2795
+ parens,
2796
+ brackets,
2797
+ braces,
2798
+ unsafe_name,
2799
+ )
2800
+ ),
2801
+ collapse_non_syntactic_newlines_handle,
2781
2802
  )
2782
2803
  unsafe_xonsh_parser, _impl_call_ref = disable_inside(
2783
2804
  single_input - end_marker,
coconut/constants.py CHANGED
@@ -1072,7 +1072,7 @@ all_reqs = {
1072
1072
 
1073
1073
  # min versions are inclusive
1074
1074
  unpinned_min_versions = {
1075
- "cPyparsing": (2, 4, 7, 2, 4, 1),
1075
+ "cPyparsing": (2, 4, 7, 2, 4, 3),
1076
1076
  ("pre-commit", "py3"): (4,),
1077
1077
  ("psutil", "py3"): (7,),
1078
1078
  "jupyter": (1, 1),
@@ -1214,6 +1214,9 @@ classifiers = (
1214
1214
  "Programming Language :: Python :: 3.10",
1215
1215
  "Programming Language :: Python :: 3.11",
1216
1216
  "Programming Language :: Python :: 3.12",
1217
+ "Programming Language :: Python :: 3.13",
1218
+ "Programming Language :: Python :: 3.14",
1219
+ "Programming Language :: Python :: 3.15",
1217
1220
  "Programming Language :: Other",
1218
1221
  "Programming Language :: Other Scripting Engines",
1219
1222
  "Programming Language :: Python :: Implementation :: CPython",
coconut/icoconut/root.py CHANGED
@@ -6,7 +6,7 @@
6
6
  # -----------------------------------------------------------------------------------------------------------------------
7
7
 
8
8
  """
9
- Author: Evan Hubinger
9
+ Authors: Evan Hubinger, Claude
10
10
  License: Apache 2.0
11
11
  Description: The Coconut IPython kernel.
12
12
  """
@@ -22,6 +22,7 @@ from coconut.root import * # NOQA
22
22
  import os
23
23
  import sys
24
24
  import logging
25
+ import inspect
25
26
 
26
27
  try:
27
28
  import asyncio
@@ -52,7 +53,7 @@ from coconut.compiler.util import should_indent, paren_change, get_comment
52
53
  from coconut.command.util import Runner
53
54
 
54
55
  try:
55
- from IPython.core.interactiveshell import InteractiveShellABC
56
+ from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
56
57
  from IPython.core.compilerop import CachingCompiler
57
58
  from IPython.terminal.embed import InteractiveShellEmbed
58
59
  from ipykernel.ipkernel import IPythonKernel
@@ -110,6 +111,33 @@ def syntaxerr_memoized_parse_block(code):
110
111
  raise syntax_err
111
112
 
112
113
 
114
+ def filter_kwargs_for(func, kwargs):
115
+ """Remove any kwargs that func can't accept.
116
+
117
+ ipykernel decides whether to pass new keyword arguments (e.g. cell_id, cell_meta)
118
+ to run_cell by inspecting our signature, so we need to accept **kwargs, but then
119
+ only forward the ones that the underlying IPython method actually supports."""
120
+ if not kwargs:
121
+ return kwargs
122
+ try:
123
+ if hasattr(inspect, "signature"):
124
+ params = inspect.signature(func).parameters
125
+ if any(p.kind == p.VAR_KEYWORD for p in params.values()):
126
+ return kwargs
127
+ accepted = set(
128
+ name for name, p in params.items()
129
+ if p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY)
130
+ )
131
+ else:
132
+ argspec = inspect.getargspec(func)
133
+ if argspec.keywords is not None:
134
+ return kwargs
135
+ accepted = set(argspec.args)
136
+ except (TypeError, ValueError):
137
+ return kwargs
138
+ return dict((k, v) for k, v in kwargs.items() if k in accepted)
139
+
140
+
113
141
  # -----------------------------------------------------------------------------------------------------------------------
114
142
  # KERNEL:
115
143
  # -----------------------------------------------------------------------------------------------------------------------
@@ -256,17 +284,20 @@ def init_user_ns(self):
256
284
  RUNNER.update_vars(self.user_ns_hidden)
257
285
 
258
286
  @override
259
- def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None, **kwargs):
287
+ def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True, **kwargs):
260
288
  """Version of run_cell that always uses shell_futures."""
261
- # cell_id is just ignored because we don't use it but we have to have it because
262
- # the presence of **kwargs means ipykernel.kernelbase._accepts_cell_id thinks we do
289
+ # the presence of **kwargs means ipykernel thinks we accept new arguments like
290
+ # cell_id and cell_meta, so we have to filter out any that IPython doesn't support
291
+ # (we check InteractiveShell since ZMQInteractiveShell.run_cell just forwards *args, **kwargs)
292
+ kwargs = filter_kwargs_for(InteractiveShell.run_cell, kwargs)
263
293
  return super({cls}, self).run_cell(raw_cell, store_history, silent, shell_futures=True, **kwargs)
264
294
 
265
- if asyncio is not None:
295
+ if asyncio is not None and hasattr(InteractiveShell, "run_cell_async"):
266
296
  @override
267
- {coroutine}def run_cell_async(self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None, **kwargs):
297
+ {coroutine}def run_cell_async(self, raw_cell, store_history=False, silent=False, shell_futures=True, **kwargs):
268
298
  """Version of run_cell_async that always uses shell_futures."""
269
299
  # same as above
300
+ kwargs = filter_kwargs_for(InteractiveShell.run_cell_async, kwargs)
270
301
  return super({cls}, self).run_cell_async(raw_cell, store_history, silent, shell_futures=True, **kwargs)
271
302
 
272
303
  @override
coconut/root.py CHANGED
@@ -26,7 +26,7 @@ import sys as _coconut_sys
26
26
  VERSION = "3.2.0"
27
27
  VERSION_NAME = None
28
28
  # False for release, int >= 1 for develop
29
- DEVELOP = 15
29
+ DEVELOP = 17
30
30
  ALPHA = False # for pre releases rather than post releases
31
31
 
32
32
  assert DEVELOP is False or DEVELOP >= 1, "DEVELOP must be False or an int >= 1"
@@ -913,6 +913,9 @@ class TestShell(unittest.TestCase):
913
913
  def test_pipe(self):
914
914
  call('echo ' + escape(coconut_snip) + "| coconut -s", shell=True, assert_output=True)
915
915
 
916
+ def test_code_interact(self):
917
+ call(["coconut", "-s", "-c", coconut_snip, "--interact"], assert_output=True, assert_output_only_at_end=False)
918
+
916
919
  def test_api(self):
917
920
  call_python(["-c", 'from coconut.api import parse; exec(parse("' + coconut_snip + '"))'], assert_output=True)
918
921
 
@@ -998,6 +1001,22 @@ class TestShell(unittest.TestCase):
998
1001
  expect_retcode=0 if not WINDOWS else None,
999
1002
  )
1000
1003
 
1004
+ def test_kernel_run_cell_kwargs(self):
1005
+ # newer ipykernels pass extra kwargs (cell_id, cell_meta) that older IPythons don't accept (#908)
1006
+ call_python(
1007
+ ["-c", "\n".join((
1008
+ "from coconut.icoconut.root import CoconutShell, filter_kwargs_for",
1009
+ "def old_run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True, cell_id=None): pass",
1010
+ "assert filter_kwargs_for(old_run_cell, dict(cell_id=1, cell_meta=2)) == dict(cell_id=1)",
1011
+ "assert filter_kwargs_for(lambda **kwargs: None, dict(cell_id=1, cell_meta=2)) == dict(cell_id=1, cell_meta=2)",
1012
+ "res = CoconutShell.instance().run_cell('x = 1 |> (.+1)', cell_id='abc', cell_meta=dict(cellId='abc'))",
1013
+ "assert res.success, res",
1014
+ "assert CoconutShell.instance().user_ns['x'] == 2",
1015
+ "print('<success>')",
1016
+ ))],
1017
+ assert_output="<success>",
1018
+ )
1019
+
1001
1020
  def test_kernel_installation(self):
1002
1021
  assert icoconut_custom_kernel_name in list_kernel_names()
1003
1022
  call(["coconut", "--jupyter"], assert_output=kernel_installation_msg)
@@ -276,7 +276,7 @@ def primary_test_2() -> bool:
276
276
  assert not (is not)(False, False)
277
277
  assert (True is not .)(1)
278
278
  assert (. is not True)(1)
279
- a_dict = {}
279
+ a_dict: dict = {}
280
280
  a_dict[1] = 1
281
281
  a_dict[3] = 2
282
282
  a_dict[2] = 3
@@ -13,7 +13,7 @@ def non_py26_test() -> bool:
13
13
  assert test["a"] == 1
14
14
  exec("a = 2", globals(), test)
15
15
  assert test["a"] == 2
16
- test: dict = {}
16
+ test = {}
17
17
  exec("b = mod(5, 3)", globals(), test)
18
18
  assert test["b"] == 2
19
19
  assert 5 .bit_length() == 3