Skip to content

Commit

Permalink
Use ruff for formatting and style
Browse files Browse the repository at this point in the history
  • Loading branch information
larsevj committed Apr 30, 2024
1 parent 3bf6c8e commit a59d9e3
Show file tree
Hide file tree
Showing 20 changed files with 300 additions and 230 deletions.
18 changes: 11 additions & 7 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,27 @@ jobs:
runs-on: ${{ matrix.os }}

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
with:
fetch-depth: 0

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}

- name: Install dependencies
run: |
pip install -r requirements.txt
pip install --upgrade setuptools
pip install -r dev-requirements.txt -r requirements.txt
- name: Test
run: |
pytest -v tests
pytest -sv tests
- name: Style
run: |
ruff check cwrap tests
ruff format cwrap tests --check
publish:
Expand All @@ -46,7 +50,7 @@ jobs:
fetch-depth: 0

- name: Set up Python 3.8
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: 3.8

Expand All @@ -56,7 +60,7 @@ jobs:
pip wheel . --no-deps -w dist
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@v1.3.1
uses: pypa/gh-action-pypi-publish@v1.8.14
with:
user: __token__
password: ${{ secrets.pypi_password }}
40 changes: 25 additions & 15 deletions cwrap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,36 @@
FILE pointer.
"""

try: from .version import version as __version__
except ImportError: __version__ = '0.0.0'
try:
from .version import version as __version__
except ImportError:
__version__ = "0.0.0"

__author__ = 'Statoil ASA'
__copyright__ = 'Copyright 2016, Statoil ASA'
__author__ = "Statoil ASA"
__copyright__ = "Copyright 2016, Statoil ASA"
__credits__ = __author__
__license__ = 'GPL'
__license__ = "GPL"
__maintainer__ = __author__
__email__ = '[email protected]'
__status__ = 'Prototype'
__email__ = "[email protected]"
__status__ = "Prototype"

from .basecclass import BaseCClass
from .basecenum import BaseCEnum
from .basecvalue import BaseCValue

from .cfile import CFILE, copen as open
from .clib import load, lib_name

from .cfile import CFILE
from .cfile import copen as open
from .clib import lib_name, load
from .metacwrap import MetaCWrap
from .prototype import REGISTERED_TYPES, Prototype, PrototypeError

__all__ = ['BaseCClass', 'BaseCEnum', 'BaseCValue', 'CFILE', 'open',
'MetaCWrap', 'Prototype', 'load', 'lib_name']
from .prototype import REGISTERED_TYPES, Prototype, PrototypeError # noqa

__all__ = [
"BaseCClass",
"BaseCEnum",
"BaseCValue",
"CFILE",
"open",
"MetaCWrap",
"Prototype",
"load",
"lib_name",
]
54 changes: 27 additions & 27 deletions cwrap/basecclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,27 @@
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.

from __future__ import (absolute_import, division,
print_function, unicode_literals)
from __future__ import absolute_import, division, print_function, unicode_literals

import ctypes

import six

import ctypes
from .metacwrap import MetaCWrap


@six.add_metaclass(MetaCWrap)
class BaseCClass(object):
class BaseCClass:
namespaces = {}

def __init__(self, c_pointer, parent=None, is_reference=False):
if not c_pointer:
raise ValueError("Must have a valid (not null) pointer value!")

if c_pointer < 0:
raise ValueError("The pointer value is negative! This may be correct, but usually is not!")
raise ValueError(
"The pointer value is negative! This may be correct, but usually is not!"
)

self.__c_pointer = c_pointer
self.__parent = parent
Expand All @@ -52,7 +55,7 @@ def _address(self):
return self.__c_pointer

def _ad_str(self):
return 'at 0x%x' % self._address()
return f"at 0x{self._address():x}"

@classmethod
def from_param(cls, c_class_object):
Expand All @@ -61,14 +64,16 @@ def from_param(cls, c_class_object):

if c_class_object is None:
return ctypes.c_void_p()
else:
return ctypes.c_void_p(c_class_object.__c_pointer)

return ctypes.c_void_p(c_class_object.__c_pointer)

@classmethod
def createPythonObject(cls, c_pointer):
if c_pointer is not None:
new_obj = cls.__new__(cls)
BaseCClass.__init__(new_obj, c_pointer=c_pointer, parent=None, is_reference=False)
BaseCClass.__init__(
new_obj, c_pointer=c_pointer, parent=None, is_reference=False
)
return new_obj
else:
return None
Expand All @@ -77,7 +82,9 @@ def createPythonObject(cls, c_pointer):
def createCReference(cls, c_pointer, parent=None):
if c_pointer is not None:
new_obj = cls.__new__(cls)
BaseCClass.__init__(new_obj, c_pointer=c_pointer, parent=parent, is_reference=True)
BaseCClass.__init__(
new_obj, c_pointer=c_pointer, parent=parent, is_reference=True
)
return new_obj
else:
return None
Expand All @@ -90,7 +97,6 @@ def convertToCReference(self, parent):
self.__is_reference = True
self.__parent = parent


def setParent(self, parent=None):
if self.__is_reference:
self.__parent = parent
Expand All @@ -100,7 +106,7 @@ def setParent(self, parent=None):
return self

def isReference(self):
""" @rtype: bool """
"""@rtype: bool"""
return self.__is_reference

def parent(self):
Expand All @@ -113,7 +119,7 @@ def __eq__(self, other):
if isinstance(other, BaseCClass):
return self.__c_pointer == other.__c_pointer
else:
return super(BaseCClass , self) == other
return super(BaseCClass, self) == other

def __hash__(self):
# Similar to last resort comparison; this returns the hash of the
Expand All @@ -123,37 +129,31 @@ def __hash__(self):
def free(self):
raise NotImplementedError("A BaseCClass requires a free method implementation!")

def _create_repr(self, args = ''):
def _create_repr(self, args=""):
"""Representation on the form (e.g.) 'EclFile(...) at 0x1729'."""
return "{0}({1}) {2}".format(self.__class__.__name__, args, self._ad_str())
return f"{self.__class__.__name__}({args}) {self._ad_str()}"

def __repr__(self):
"""Representation on the form (e.g.) 'EclFile(...) at 0x1729'."""
return self._create_repr()

def __del__(self):
if self.free is not None:
if not self.__is_reference:
# Important to check the c_pointer; in the case of failed object creation
# we can have a Python object with c_pointer == None.
if self.__c_pointer:
self.free()
if self.free is not None and not self.__is_reference and self.__c_pointer:
# Important to check the c_pointer; in the case of failed object creation
# we can have a Python object with c_pointer == None.
self.free()

def _invalidateCPointer(self):
self.__c_pointer = None


def __bool__(self):
"""The BaseCClass instance will evaluate to true if it is bound to an
underlying C object, otherwise it will evaluate to False. More
elaborate bool tests should be implemented in the derived
class.
"""
if self.__c_pointer:
return True
else:
return False

return bool(self.__c_pointer)

def __nonzero__(self):
return self.__bool__( )
return self.__bool__()
24 changes: 10 additions & 14 deletions cwrap/basecenum.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


@six.add_metaclass(MetaCWrap)
class BaseCEnum(object):
class BaseCEnum:
enum_namespace = {}

def __init__(self, *args, **kwargs):
Expand All @@ -36,7 +36,7 @@ def __new__(cls, *args, **kwargs):
enum = cls.__resolveEnum(args[0])

if enum is None:
raise ValueError("Unknown enum value: %i" % args[0])
raise ValueError(f"Unknown enum value: {args[0]}")

return enum
else:
Expand All @@ -57,7 +57,7 @@ def from_string(cls, name):
if enum.name == name:
return enum

raise ValueError("No such enum:%s" % name)
raise ValueError(f"No such enum: {name}")

@classmethod
def addEnum(cls, name, value):
Expand Down Expand Up @@ -102,7 +102,7 @@ def __repr__(self):
cn = self.__class__.__name__
na = self.name
va = self.value
return '%s(name = "%s", value = %s)' % (cn, na, va)
return f'{cn}(name = "{na}", value = {va})'

def __add__(self, other):
self.__assertOtherIsSameType(other)
Expand All @@ -126,7 +126,7 @@ def __and__(self, other):

def __int__(self):
return self.value

def __index__(self):
return self.value

Expand All @@ -136,7 +136,7 @@ def __contains__(self, item):
@classmethod
def __createEnum(cls, value):
enum = cls.__new__(cls)
enum.name = "Unnamed '%s' enum with value: %i" % (str(cls.__name__), value)
enum.name = f"Unnamed '{cls.__name__}' enum with value: {value}"
enum.value = value
return enum

Expand All @@ -159,20 +159,16 @@ def __resolveEnum(cls, value):
def __assertOtherIsSameType(self, other):
assert isinstance(
other, self.__class__
), "Can only operate on enums of same type: %s =! %s" % (
self.__class__.__name__,
other.__class__.__name__,
)
), f"Can only operate on enums of same type: {self.__class__.__name__} =! {other.__class__.__name__}"

@classmethod
def populateEnum(cls, library, enum_provider_function):
try:
func = getattr(library, enum_provider_function)
except AttributeError:
except AttributeError as err:
raise ValueError(
"Could not find enum description function: %s - can not load enum: %s."
% (enum_provider_function, cls.__name__)
)
f"Could not find enum description function: {enum_provider_function} - can not load enum: {cls.__name__}."
) from err

func.restype = ctypes.c_char_p
func.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_int)]
Expand Down
45 changes: 36 additions & 9 deletions cwrap/basecvalue.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,57 @@
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.

from __future__ import (absolute_import, division,
print_function, unicode_literals)
from __future__ import absolute_import, division, print_function, unicode_literals

from ctypes import (
c_bool,
c_byte,
c_char,
c_double,
c_float,
c_int,
c_long,
c_short,
c_ubyte,
c_uint,
c_ulong,
c_ushort,
pointer,
)

import six

from ctypes import (pointer, c_long, c_int, c_bool, c_float, c_double, c_byte,
c_short, c_char, c_ubyte, c_ushort, c_uint, c_ulong)

from .metacwrap import MetaCWrap


@six.add_metaclass(MetaCWrap)
class BaseCValue(object):
class BaseCValue:
DATA_TYPE = None
LEGAL_TYPES = [c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_bool, c_char, c_float, c_double]
LEGAL_TYPES = [
c_byte,
c_ubyte,
c_short,
c_ushort,
c_int,
c_uint,
c_long,
c_ulong,
c_bool,
c_char,
c_float,
c_double,
]

def __init__(self, value):
super(BaseCValue, self).__init__()

if not self.DATA_TYPE in self.LEGAL_TYPES:
raise ValueError("DATA_TYPE must be one of these CTypes classes: %s" % BaseCValue.LEGAL_TYPES)
raise ValueError(
f"DATA_TYPE must be one of these CTypes classes: {BaseCValue.LEGAL_TYPES}"
)

self.__value = self.cast(value)


def value(self):
return self.__value.value

Expand Down
Loading

0 comments on commit a59d9e3

Please sign in to comment.