Skip to content

Commit 499b1a6

Browse files
authored
Merge pull request #14 from openmicroanalysis/dataclass
Dataclass
2 parents 9ca07d3 + e639ea3 commit 499b1a6

File tree

10 files changed

+665
-858
lines changed

10 files changed

+665
-858
lines changed

.travis.yml

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
sudo: false
2+
dist: xenial
23
language: python
3-
cache:
4-
directories:
5-
- $HOME/.pip-cache/
6-
matrix:
7-
include:
8-
- python: '3.6'
9-
os: linux
4+
cache: pip
5+
python:
6+
- '3.6'
7+
- '3.7'
108
install:
11-
- pip install --cache-dir $HOME/.pip-cache --upgrade pip codecov
12-
- pip install --cache-dir $HOME/.pip-cache --upgrade -e .[build,develop]
9+
- pip install --upgrade pip codecov
10+
- pip install --upgrade -e .[build,develop]
1311
script:
14-
- nosetests
15-
after_success: codecov
12+
- pytest
13+
after_success:
14+
- codecov
1615
notifications:
1716
email: false

appveyor.yml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
environment:
2+
3+
matrix:
4+
- PYTHON: "C:\\Python36-x64"
5+
- PYTHON: "C:\\Python37-x64"
6+
7+
install:
8+
- "%PYTHON%\\python.exe -m pip install --upgrade pip wheel codecov"
9+
- "%PYTHON%\\python.exe -m pip install --upgrade -e .[build,develop]"
10+
11+
build: off
12+
13+
test_script:
14+
- "%PYTHON%\\Scripts\\pytest.exe"

pyxray/cbook.py

Lines changed: 0 additions & 153 deletions
Original file line numberDiff line numberDiff line change
@@ -3,166 +3,13 @@
33
"""
44

55
# Standard library modules.
6-
import weakref
76

87
# Third party modules.
98

109
# Local modules.
1110

1211
# Globals and constants variables.
1312

14-
class Immutable(type):
15-
"""
16-
Make a class immutable.
17-
The attribute cannot be added or modified.
18-
The attributes should be defined by the argument ``attrs`` in the class
19-
definition::
20-
21-
class Foo(metaclass=Immutable, attrs=('bar',)):
22-
pass
23-
24-
The constructor of the class then takes the same number of arguments::
25-
26-
foo = Foo('abc')
27-
foo.bar # returns 'abc'
28-
"""
29-
30-
def __new__(cls, name, bases, methods, *, attrs=None):
31-
# Make a __new__ function and add to the class dict
32-
def __new__(cls, *args, **kwargs):
33-
args = list(args)
34-
35-
for key, value in kwargs.items():
36-
try:
37-
index = attrs.index(key)
38-
except ValueError:
39-
raise TypeError('Unknown argument: {0}'.format(key))
40-
args.insert(index, value)
41-
42-
if len(args) != len(attrs):
43-
raise TypeError('Expected {} arguments'.format(len(attrs)))
44-
45-
obj = object.__new__(cls)
46-
obj._values = tuple(args)
47-
obj._attrs = tuple(attrs)
48-
49-
return obj
50-
methods['__new__'] = __new__
51-
52-
# Configure __slots__
53-
methods['__slots__'] = ('__weakref__', '_values', '_attrs')
54-
55-
# Configure __hash__
56-
methods['__hash__'] = lambda s: hash((s.__class__, s._values))
57-
58-
# Configure copy
59-
methods['__copy__'] = lambda s: s
60-
methods['__deepcopy__'] = lambda s, memo: s
61-
62-
# Configure pickle
63-
methods['__getnewargs_ex__'] = lambda s: (s._values, {})
64-
65-
# Populate a dictionary of field property accessors
66-
methods.update({name: property(lambda s, n=n: s._values[n])
67-
for n, name in enumerate(attrs)})
68-
69-
cls = super().__new__(cls, name, bases, methods)
70-
71-
return cls
72-
73-
def __init__(self, name, bases, methods, *, attrs=None):
74-
super().__init__(name, bases, methods)
75-
76-
class Cachable(type):
77-
"""
78-
From Beazley, D. & Jones, B. K. (2013) Python Cookbook, O'Reilly.
79-
80-
Creates a cache using the arguments of :meth:`__init__`.
81-
"""
82-
83-
def __init__(self, name, bases, methods):
84-
super().__init__(name, bases, methods)
85-
self.__cache = weakref.WeakValueDictionary()
86-
87-
def __call__(self, *args, **kwargs):
88-
cachekey = args + tuple(sorted(kwargs.items()))
89-
if cachekey in self.__cache:
90-
return self.__cache[cachekey]
91-
92-
# Create object
93-
obj = super().__call__(*args, **kwargs)
94-
95-
# Cached
96-
self.__cache[cachekey] = obj
97-
98-
return obj
99-
100-
class Validable(type):
101-
"""
102-
Validates the object before it is created using the arguments from the
103-
:meth:`__init__`.
104-
The class method :meth:`validate` should be overwritten.
105-
There are three options for the return values of the :meth:`validate`:
106-
107-
1. return ``None`` or no return at all: the same arguments and
108-
keyword arguments are passed to the constructor
109-
2. return a :class:`tuple` and a :class:`dict`: the tuple contains
110-
updated arguments and the dict, updated keyword-arguments
111-
3. return a :class:`tuple`: the tuple contains updated arguments.
112-
No keyword-arguments is passed to the constructor.
113-
114-
In all other cases, a :exc:`ValueError` is raised.
115-
"""
116-
117-
def validate(cls, *args, **kwargs): #@NoSelf #pragma: no cover
118-
return args
119-
120-
def __call__(self, *args, **kwargs):
121-
out = self.validate(*args, **kwargs)
122-
if out is not None:
123-
if len(out) == 2 and \
124-
isinstance(out[0], tuple) and \
125-
isinstance(out[1], dict):
126-
args, kwargs = out
127-
elif isinstance(out, tuple):
128-
args = out
129-
kwargs = {}
130-
else: #pragma: no cover
131-
raise ValueError('Unknown type of return arguments')
132-
133-
return super().__call__(*args, **kwargs)
134-
135-
class Reprable(type):
136-
"""
137-
Construct the __repr__ of an object based on the :meth:`_repr_inner` method
138-
if it is defined.
139-
"""
140-
141-
def __new__(cls, name, bases, methods, *args, **kwargs):
142-
def __repr__(self):
143-
s = '{0}('.format(self.__class__.__name__)
144-
145-
if hasattr(self, '_repr_inner'):
146-
s += self._repr_inner()
147-
148-
else:
149-
inner = []
150-
for attr, value in zip(self._attrs, self._values):
151-
if hasattr(value, '_repr_inner'):
152-
inner.append(value._repr_inner())
153-
elif '_' in attr:
154-
_, unit = attr.rsplit('_', 1)
155-
inner.append('{0:.4e}{1}'.format(value, unit))
156-
else:
157-
inner.append('{0}={1}'.format(attr, value))
158-
s += ', '.join(inner)
159-
160-
s += ')'
161-
return s
162-
methods['__repr__'] = __repr__
163-
164-
return super().__new__(cls, name, bases, methods, *args, **kwargs)
165-
16613
class ProgressMixin:
16714

16815
def update(self, progress):

0 commit comments

Comments
 (0)