Skip to content

Commit

Permalink
Merge pull request #22 from enthought/feat/python3
Browse files Browse the repository at this point in the history
Python 3 Port
  • Loading branch information
rkern committed Oct 30, 2018
2 parents 5b5ebd0 + 70f81d2 commit 042e701
Show file tree
Hide file tree
Showing 60 changed files with 471 additions and 363 deletions.
5 changes: 2 additions & 3 deletions .travis.yml
Expand Up @@ -2,8 +2,9 @@ language: python
sudo: false
python:
- 2.7
- 2.6
- 3.4
- 3.5
- 3.6
addons:
apt:
packages:
Expand All @@ -25,8 +26,6 @@ install:
- pip install cython
- pip install -r travis-ci-requirements.txt
- python setup.py develop
# there is a circular dependency with codetools
- pip install git+http://github.com/enthought/blockcanvas.git#egg=blockcanvas
before_script:
- cp .coveragerc integrationtests
- cd integrationtests
Expand Down
1 change: 1 addition & 0 deletions codetools/__init__.py
Expand Up @@ -7,5 +7,6 @@
__version__ = 'not-built'

__requires__ = [
'six',
'traits',
]
2 changes: 1 addition & 1 deletion codetools/blocks/analysis.py
Expand Up @@ -22,7 +22,7 @@
from ..util import graph
from ..util.graph import closure
from ..util.sequence import \
all, disjoint, intersect, is_sequence, union
disjoint, intersect, is_sequence, union
from ..util import tree

# Extend compiler.ast.Node with a structure-preserving children query
Expand Down
2 changes: 1 addition & 1 deletion codetools/blocks/ast_25/unparse_.py
Expand Up @@ -505,7 +505,7 @@ def testdir(a):
print 'Testing %s' % fullname
try:
roundtrip(fullname, output)
except Exception, e:
except Exception as e:
print ' Failed to compile, exception is %s' % repr(e)
elif os.path.isdir(fullname):
testdir(fullname)
Expand Down
18 changes: 10 additions & 8 deletions codetools/blocks/block.py
Expand Up @@ -7,14 +7,16 @@
#
'Simple blocks of python code with dependency analysis.'

from __future__ import absolute_import
from __future__ import absolute_import, print_function

import compiler
from compiler.ast import Module, Node, Stmt
from traceback import format_exc
import types
from uuid import UUID, uuid4

from six import exec_

from traits.api import (Bool, Dict, Either, HasTraits,
Instance, List, Property, Str,
cached_property, Event)
Expand Down Expand Up @@ -250,15 +252,15 @@ def _print_debug_graph(self, graph):
""" Only to be used for debugging- prints each node of the graph
with its immediate dependents following
"""
print "--------------------------------------"
print("--------------------------------------")
for k in graph.keys():
if isinstance(k, Block):
print k.ast
print(k.ast)
for dep in graph[k]:
if isinstance(dep, Block):
print " %s" % dep.ast
print(" %s" % dep.ast)
else:
print " '%s'" % dep[0]
print(" '%s'" % dep[0])

###########################################################################
# Block public interface
Expand Down Expand Up @@ -295,14 +297,14 @@ def execute(self, local_context, global_context = {}, continue_on_errors=False):
not continue_on_errors:
if self.filename:
local_context['__file__'] = self.filename
exec self._code in global_context, local_context
exec_(self._code, global_context, local_context)
else:
if continue_on_errors:
exceptions = []
for block in self.sub_blocks:
try:
block.execute(local_context, global_context)
except Exception, e:
except Exception as e:
# save the current traceback
e.traceback = format_exc()
exceptions.append(e)
Expand Down Expand Up @@ -581,7 +583,7 @@ def get_function(self, inputs=[], outputs=[]):
leno = len(outputs)
def simplefunc(*args):
if len(args) != leni:
raise ValueError, "Must have %d inputs" % leni
raise ValueError("Must have %d inputs" % leni)
namespace = {}
for i, arg in enumerate(args):
namespace[inputs[i]] = arg
Expand Down
2 changes: 1 addition & 1 deletion codetools/blocks/decorators.py
Expand Up @@ -118,7 +118,7 @@ def code():
callframe = sys._getframe(backframes)
filename = callframe.f_code.co_filename
if filename == '<stdin>':
raise ValueError, "Decorator can't be used here."
raise ValueError("Decorator can't be used here.")
elif filename == '<ipython console>':
s = findsource_ipython(callframe, func.func_name)
else:
Expand Down
4 changes: 3 additions & 1 deletion codetools/blocks/namespace_tools.py
Expand Up @@ -11,6 +11,8 @@
"""
from __future__ import absolute_import

from six import exec_

from .decorators import func2str

##############################################################################
Expand Down Expand Up @@ -76,7 +78,7 @@ def namespace_function(*args, **kw):
ns.update(positional)
globs = function.func_globals

exec code_object in globs, ns
exec_(code_object, globs, ns)

# Save the original function name in the namespace as
# the attribute '_func_name'.
Expand Down
6 changes: 4 additions & 2 deletions codetools/blocks/parser_.py
Expand Up @@ -11,6 +11,7 @@
from compiler.transformer import Transformer
import token


class BlockTransformer(Transformer, object):
'Specialize how code parses into ASTs for Blocks.'

Expand All @@ -21,9 +22,10 @@ class BlockTransformer(Transformer, object):
# What we rewrite 'from %s import *' into
_rewrite_wildcard_into = '''
import %s as __module
import six as __six
for name in dir(__module):
exec '%%s = __module.%%s' %% (name, name)
del __module
__six.exec_('%%s = __module.%%s' %% (name, name))
del __module, __six
'''

###########################################################################
Expand Down
8 changes: 8 additions & 0 deletions codetools/blocks/tests/__init__.py
@@ -0,0 +1,8 @@
from unittest import SkipTest

import six


def setup_package():
if six.PY3:
raise SkipTest("codetools.blocks not ported to Python 3")
4 changes: 2 additions & 2 deletions codetools/blocks/tests/error_continue_test.py
Expand Up @@ -28,7 +28,7 @@ def test_single_exception(self):
try:
b.execute(ctx, continue_on_errors=True)
assert False #We should have thrown
except Exception, e:
except Exception as e:
assert isinstance(e, ValueError)
assert ctx.has_key('d')
return
Expand All @@ -39,7 +39,7 @@ def test_multi_exception(self):
try:
b.execute(ctx, continue_on_errors=True)
assert False #We should have thrown
except Exception, e:
except Exception as e:
assert isinstance(e, CompositeException)
assert len(e.exceptions) == 2
return
Expand Down
5 changes: 4 additions & 1 deletion codetools/blocks/tests/test_namespace_tools.py
@@ -1,5 +1,8 @@
import os

from numpy.testing import assert_equal, assert_
from six import exec_

from codetools.blocks.namespace_tools import *

def test_Namespace_class():
Expand Down Expand Up @@ -89,7 +92,7 @@ def test_namespace_in_execfile():
def test_namespace_in_exec():
# Verify that namespace decorator does *NOT* work in exec'd code.
dic = {'a':2, 'namespace':namespace}
exec code_to_exec in dic
exec_(code_to_exec, dic, dic)
assert_equal(set(dic.keys()), set(['a', '__builtins__', 'namespace',
'f', 'ns']))
ns = dic['ns']
Expand Down
2 changes: 1 addition & 1 deletion codetools/blocks2/analysis.py
Expand Up @@ -12,7 +12,7 @@
from ..util import graph
from ..util.graph import closure
from ..util.sequence import \
all, disjoint, intersect, is_sequence, union
disjoint, intersect, is_sequence, union
from ..util import tree

# Extend compiler.ast.Node with a structure-preserving children query
Expand Down
22 changes: 13 additions & 9 deletions codetools/blocks2/block.py
Expand Up @@ -4,6 +4,8 @@
from the old compiler.ast module. -Anthony Scopatz
"""

from __future__ import print_function

import ast
#from ast import mod, stmt, expr, expr_context, slice, boolop, operator, \
# unaryop, cmpop, comprehension, excepthandler, arguments, keyword, alias
Expand All @@ -13,6 +15,8 @@
import types
from uuid import UUID, uuid4

from six import exec_

from traits.api import (Bool, Dict, Either, HasTraits,
Instance, List, Property, Str,
cached_property, Event)
Expand All @@ -21,9 +25,9 @@
from ..util import graph
from ..util.sequence import is_sequence

from analysis import NameFinder
from .analysis import NameFinder

from block_transformer import BlockTransformer
from .block_transformer import BlockTransformer
from codetools.blocks.compiler_unparse import unparse

###############################################################################
Expand Down Expand Up @@ -252,15 +256,15 @@ def _print_debug_graph(self, graph):
""" Only to be used for debugging- prints each node of the graph
with its immediate dependents following
"""
print "--------------------------------------"
print("--------------------------------------")
for k in graph.keys():
if isinstance(k, Block):
print k.ast
print(k.ast)
for dep in graph[k]:
if isinstance(dep, Block):
print " %s" % dep.ast
print(" %s" % dep.ast)
else:
print " '%s'" % dep[0]
print(" '%s'" % dep[0])

###########################################################################
# Block public interface
Expand Down Expand Up @@ -297,14 +301,14 @@ def execute(self, local_context, global_context = {}, continue_on_errors=False):
not continue_on_errors:
if self.filename:
local_context['__file__'] = self.filename
exec self._code in global_context, local_context
exec_(self._code, global_context, local_context)
else:
if continue_on_errors:
exceptions = []
for block in self.sub_blocks:
try:
block.execute(local_context, global_context)
except Exception, e:
except Exception as e:
# save the current traceback
e.traceback = format_exc()
exceptions.append(e)
Expand Down Expand Up @@ -584,7 +588,7 @@ def get_function(self, inputs=[], outputs=[]):
leno = len(outputs)
def simplefunc(*args):
if len(args) != leni:
raise ValueError, "Must have %d inputs" % leni
raise ValueError("Must have %d inputs" % leni)
namespace = {}
for i, arg in enumerate(args):
namespace[inputs[i]] = arg
Expand Down
5 changes: 3 additions & 2 deletions codetools/blocks2/block_transformer.py
Expand Up @@ -11,9 +11,10 @@ class BlockTransformer(NodeTransformer, object):

# What we rewrite 'from %s import *' into
_rewrite_wildcard_into = ("import %s as __module\n"
"import six as __six\n"
"for name in dir(__module):\n"
" exec '%%s = __module.%%s' %% (name, name)\n"
"del __module\n")
" __six.exec_('%%s = __module.%%s' %% (name, name))\n"
"del __module, __six\n")

###########################################################################
# Transformer public interface
Expand Down
8 changes: 8 additions & 0 deletions codetools/blocks2/tests/__init__.py
@@ -0,0 +1,8 @@
from unittest import SkipTest

import six


def setup_package():
if six.PY3:
raise SkipTest("codetools.blocks not ported to Python 3")
6 changes: 2 additions & 4 deletions codetools/contexts/adapter/adapter_manager_mixin.py
Expand Up @@ -8,19 +8,17 @@
from __future__ import absolute_import

# Enthought imports
from traits.api import HasTraits, List, implements
from traits.api import HasTraits, List

# Local imports
from .i_adapter_manager import IAdapterManager


class AdapterManagerMixin(HasTraits):
class AdapterManagerMixin(IAdapterManager):
""" Handles management of an adapter stack for objects that implement
IContext.
"""

implements(IAdapterManager)

### Private AdapterManagerMixin traits #####################################

# List of adapters that modify the values of the context.
Expand Down
5 changes: 3 additions & 2 deletions codetools/contexts/adapter/i_adapter.py
@@ -1,6 +1,7 @@
from traits.api import Interface
from traits.api import ABCHasTraits

class IAdapter(Interface):

class IAdapter(ABCHasTraits):
""" Handles management of an adapter stack for objects that implement
IContext.
"""
Expand Down
5 changes: 3 additions & 2 deletions codetools/contexts/adapter/i_adapter_manager.py
Expand Up @@ -8,9 +8,10 @@

from __future__ import absolute_import

from traits.api import Interface
from traits.api import ABCHasTraits

class IAdapterManager(Interface):

class IAdapterManager(ABCHasTraits):
""" Handles management of an adapter stack for objects that implement
IContext.
"""
Expand Down
4 changes: 4 additions & 0 deletions codetools/contexts/adapter/masking_adapter.py
Expand Up @@ -16,6 +16,7 @@

# Enthought library imports
from traits.api import Any, HasTraits
from scimath.units.api import UnitArray

# Local imports
from .i_adapter import IAdapter
Expand Down Expand Up @@ -91,6 +92,9 @@ def get_default_value_and_dtype(name, value):
default_value, dtype = get_default_value_and_dtype(name, value)
new = self._empty_of_local_shape(context, dtype=dtype)
new.fill(default_value)
if isinstance(value, UnitArray):
new = new.view(UnitArray)
new.units = value.units
###new[self.mask] = value
###return name, new

Expand Down
3 changes: 2 additions & 1 deletion codetools/contexts/adapter/name_adapter.py
Expand Up @@ -14,6 +14,7 @@
# Local imports
from .i_adapter import IAdapter


@provides(IAdapter)
class NameAdapter(HasTraits):
""" Maps more descriptive names provided by the user to names in the context
Expand Down Expand Up @@ -46,4 +47,4 @@ def adapt_keys(self):
""" Returns a list containing any keys (names) defined by this
adapter.
"""
return self.map.keys()
return list(self.map.keys())
2 changes: 1 addition & 1 deletion codetools/contexts/adapter/unit_manipulation_adapter.py
Expand Up @@ -133,7 +133,7 @@ def _convert(self, value, new_units):
# Conversion requested (new_units exist), but a converter
# wasn't found.
msg = "Unable to find converter for type %s" % type(value)
raise ConversionError, msg
raise ConversionError(msg)

return value

Expand Down

0 comments on commit 042e701

Please sign in to comment.