Skip to content

Commit

Permalink
Import ABC from collections.abc instead of collections for Python 3.9…
Browse files Browse the repository at this point in the history
… compatibility. (#485)

* Import ABC from collections.abc instead of collections for Python 3.9 compatibility.
  • Loading branch information
tirkarthi committed Jan 30, 2020
1 parent 5c22a1e commit 57c1175
Show file tree
Hide file tree
Showing 7 changed files with 25 additions and 19 deletions.
3 changes: 2 additions & 1 deletion pysb/bng.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from warnings import warn
import shutil
import collections
from collections.abc import Sequence
import pysb.pathfinder as pf
import tokenize
from pysb.logging import get_logger, EXTENDED_DEBUG
Expand Down Expand Up @@ -120,7 +121,7 @@ def _bng_param(cls, param):
return '"%s"' % param
elif isinstance(param, bool):
return 1 if param else 0
elif isinstance(param, (collections.Sequence, numpy.ndarray)):
elif isinstance(param, (Sequence, numpy.ndarray)):
return list(param)
return param

Expand Down
11 changes: 6 additions & 5 deletions pysb/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import numpy as np
import scipy.sparse
import networkx as nx
from collections.abc import Iterable, Mapping, Sequence, Set

try:
reload
Expand Down Expand Up @@ -284,7 +285,7 @@ def __init__(self, name, sites=None, site_states=None, _export=True):

# ensure sites is some kind of list (presumably of strings) but not a
# string itself
if not isinstance(sites, collections.Iterable) or \
if not isinstance(sites, Iterable) or \
isinstance(sites, basestring):
raise ValueError("sites must be a list of strings")

Expand Down Expand Up @@ -2220,7 +2221,7 @@ def __init__(self):
)


class ComponentSet(collections.Set, collections.Mapping, collections.Sequence):
class ComponentSet(Set, Mapping, Sequence):
"""
An add-and-read-only container for storing model Components.
Expand Down Expand Up @@ -2428,7 +2429,7 @@ def __and__(self, other):
# We require other to be a ComponentSet too so we know it will support
# "in" efficiently.
if not isinstance(other, ComponentSet):
return collections.Set.__and__(self, other)
return Set.__and__(self, other)
return ComponentSet(value for value in self if value in other)

def __rand__(self, other):
Expand All @@ -2452,7 +2453,7 @@ def rename(self, c, new_name):
del m[c.name]


class OdeView(collections.Sequence):
class OdeView(Sequence):
"""Compatibility shim for the Model.odes property."""

# This is necessarily coupled pretty tightly with Model. Note that we
Expand All @@ -2478,7 +2479,7 @@ def __len__(self):
return len(self.model.species)


class InitialConditionsView(collections.Sequence):
class InitialConditionsView(Sequence):
"""Compatibility shim for the Model.initial_conditions property."""

def __init__(self, model):
Expand Down
5 changes: 3 additions & 2 deletions pysb/importers/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from pysb.annotation import Annotation
import sympy
import collections
from collections.abc import Mapping
import json
import re
from sympy.parsing.sympy_parser import parse_expr
Expand Down Expand Up @@ -37,7 +38,7 @@ def _modelget(self, name):
return self.b.model.components[name]

def decode_state_value(self, sv):
if isinstance(sv, collections.Mapping) and '__object__' in sv:
if isinstance(sv, Mapping) and '__object__' in sv:
if sv['__object__'] == '__multistate__':
return MultiState(*sv['sites'])
if sv['__object__'] == 'ANY':
Expand All @@ -46,7 +47,7 @@ def decode_state_value(self, sv):
return WILD
try:
if len(sv) == 2 and isinstance(sv[0], basestring) \
and isinstance(sv[1], (int, collections.Mapping)):
and isinstance(sv[1], (int, Mapping)):
return sv[0], self.decode_state_value(sv[1])
except TypeError:
pass
Expand Down
3 changes: 2 additions & 1 deletion pysb/pattern.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import collections
from collections.abc import Iterable
from .core import ComplexPattern, MonomerPattern, Monomer, \
ReactionPattern, ANY, as_complex_pattern, DanglingBondError, \
ReusedBondError, Rule
Expand Down Expand Up @@ -191,7 +192,7 @@ def _get_bonds_in_monomer_pattern(mp):
if isinstance(sc, int):
bonds_used.append(sc)
elif not isinstance(sc, basestring) and \
isinstance(sc, collections.Iterable):
isinstance(sc, Iterable):
[bonds_used.append(b) for b in sc if isinstance(b, int)]

if pat is None:
Expand Down
15 changes: 8 additions & 7 deletions pysb/simulator/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import itertools
import sympy
import collections
from collections.abc import Mapping, Sequence
import numbers
from pysb.core import MonomerPattern, ComplexPattern, as_complex_pattern, \
Parameter, Expression, Model, ComponentSet
Expand Down Expand Up @@ -168,7 +169,7 @@ def initials_length(self):
return len(self.param_values)

def _update_initials_dict(self, initials_dict, initials_source, subs=None):
if isinstance(initials_source, collections.Mapping):
if isinstance(initials_source, Mapping):
# Can't just use .update() as we need to test
# equality with .is_equivalent_to()
for cp, value_obj in initials_source.items():
Expand All @@ -177,7 +178,7 @@ def _update_initials_dict(self, initials_dict, initials_source, subs=None):
for existing_cp in initials_dict):
continue

if isinstance(value_obj, (collections.Sequence, np.ndarray))\
if isinstance(value_obj, (Sequence, np.ndarray))\
and all(isinstance(v, numbers.Number) for v in value_obj):
value = value_obj
elif isinstance(value_obj, Expression):
Expand Down Expand Up @@ -277,17 +278,17 @@ def initials(self):

# Check potential quick return options
if self._run_initials is not None:
if not isinstance(self._run_initials, collections.Mapping) and \
if not isinstance(self._run_initials, Mapping) and \
self._initials is None:
return self._run_initials
elif not isinstance(self._initials, collections.Mapping) and \
elif not isinstance(self._initials, Mapping) and \
self._initials is not None:
return self._initials

# At this point (after dimensionality check), we can return
# self._run_initials if it's not a dictionary and not None
if self._run_initials is not None and not isinstance(
self._run_initials, collections.Mapping):
self._run_initials, Mapping):
return self._run_initials

n_sims_initials = self._check_run_initials_vs_base_initials_length()
Expand Down Expand Up @@ -331,7 +332,7 @@ def _process_incoming_initials(self, new_initials):
'MonomerPattern or ComplexPattern' %
repr(cplx_pat))
# if val is a number, convert it to a single-element array
if not isinstance(val, (collections.Sequence, np.ndarray)):
if not isinstance(val, (Sequence, np.ndarray)):
val = [val]
new_initials[cplx_pat] = np.array(val)
# otherwise, check whether simulator supports multiple
Expand Down Expand Up @@ -468,7 +469,7 @@ def _process_incoming_params(self, new_params):
raise IndexError("new_params dictionary has unknown "
"parameter name (%s)" % key)
# if val is a number, convert it to a single-element array
if not isinstance(val, collections.Sequence):
if not isinstance(val, Sequence):
val = [val]
new_params[key] = np.array(val)
# Check all elements are the same length
Expand Down
4 changes: 2 additions & 2 deletions pysb/simulator/bng.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
from pysb.core import as_complex_pattern, Parameter, \
InvalidComplexPatternException
import collections
from collections.abc import Iterable
import os


class BngSimulator(Simulator):
""" Simulate a model using BioNetGen """
_supports = {
Expand Down Expand Up @@ -111,7 +111,7 @@ def run(self, tspan=None, initials=None, param_values=None, n_runs=1,

if method == 'nf':
if population_maps is not None and (not isinstance(
population_maps, collections.Iterable) or
population_maps, Iterable) or
any(not isinstance(pm, PopulationMap) for pm in
population_maps)):
raise ValueError('population_maps should be a list of '
Expand Down
3 changes: 2 additions & 1 deletion pysb/simulator/cupsoda.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pysb.pathfinder import get_path
import sympy
import collections
from collections.abc import Iterable
try:
import pandas as pd
except ImportError:
Expand Down Expand Up @@ -168,7 +169,7 @@ def __init__(self, model, tspan=None, initials=None, param_values=None,
param_values=param_values,
verbose=verbose, **kwargs)
self.gpu = kwargs.pop('gpu', (0, ))
if not isinstance(self.gpu, collections.Iterable):
if not isinstance(self.gpu, Iterable):
self.gpu = [self.gpu]
self._obs_species_only = kwargs.pop('obs_species_only', True)
self._cleanup = kwargs.pop('cleanup', True)
Expand Down

0 comments on commit 57c1175

Please sign in to comment.