Python packaging.version.parse() Examples
The following are 30
code examples of packaging.version.parse().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
packaging.version
, or try the search function
.
Example #1
Source File: conftest.py From larq with Apache License 2.0 | 7 votes |
def keras_should_run_eagerly(request): """Fixture to run in graph and two eager modes. The modes are: - Graph mode - TensorFlow eager and Keras eager - TensorFlow eager and Keras not eager The `tf.context` sets graph/eager mode for TensorFlow. The yield is True if Keras should run eagerly. """ if request.param == "graph": if version.parse(tf.__version__) >= version.parse("2"): pytest.skip("Skipping graph mode for TensorFlow 2+.") with context.graph_mode(): yield else: with context.eager_mode(): yield request.param == "tf_keras_eager"
Example #2
Source File: __init__.py From signac with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _collect_migrations(project): schema_version = version.parse(SCHEMA_VERSION) def config_schema_version(): return version.parse(project._config['schema_version']) if config_schema_version() > schema_version: # Project config schema version is newer and therefore not supported. raise RuntimeError( "The signac schema version used by this project is {}, but signac {} " "only supports up to schema version {}. Try updating signac.".format( config_schema_version, __version__, SCHEMA_VERSION)) while config_schema_version() < schema_version: for (origin, destination), migration in MIGRATIONS.items(): if version.parse(origin) == config_schema_version(): yield (origin, destination), migration break else: raise RuntimeError( "The signac schema version used by this project is {}, but signac {} " "uses schema version {} and does not know how to migrate.".format( config_schema_version(), __version__, schema_version))
Example #3
Source File: utils.py From pipenv with MIT License | 6 votes |
def clean_requires_python(candidates): """Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes.""" all_candidates = [] sys_version = ".".join(map(str, sys.version_info[:3])) from packaging.version import parse as parse_version py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version)) for c in candidates: requires_python = _get_requires_python(c) if requires_python: # Old specifications had people setting this to single digits # which is effectively the same as '>=digit,<digit+1' if requires_python.isdigit(): requires_python = ">={0},<{1}".format( requires_python, int(requires_python) + 1 ) try: specifierset = SpecifierSet(requires_python) except InvalidSpecifier: continue else: if not specifierset.contains(py_version): continue all_candidates.append(c) return all_candidates
Example #4
Source File: _utils.py From scanpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_versions(): anndata_version = pkg_version("anndata") umap_version = pkg_version("umap-learn") if anndata_version < version.parse('0.6.10'): from . import __version__ raise ImportError( f'Scanpy {__version__} needs anndata version >=0.6.10, ' f'not {anndata_version}.\nRun `pip install anndata -U --no-deps`.' ) if umap_version < version.parse('0.3.0'): from . import __version__ # make this a warning, not an error # it might be useful for people to still be able to run it logg.warning( f'Scanpy {__version__} needs umap ' f'version >=0.3.0, not {umap_version}.' )
Example #5
Source File: main.py From conditional-motion-propagation with MIT License | 6 votes |
def main(args): with open(args.config) as f: if version.parse(yaml.version >= "5.1"): config = yaml.load(f, Loader=yaml.FullLoader) else: config = yaml.load(f) for k, v in config.items(): setattr(args, k, v) # exp path if not hasattr(args, 'exp_path'): args.exp_path = os.path.dirname(args.config) # dist init if mp.get_start_method(allow_none=True) != 'spawn': mp.set_start_method('spawn', force=True) dist_init(args.launcher, backend='nccl') # train trainer = Trainer(args) trainer.run()
Example #6
Source File: weight_process.py From conditional-motion-propagation with MIT License | 6 votes |
def main(): exp_dir = os.path.dirname(args.config) with open(args.config) as f: if version.parse(yaml.version >= "5.1"): config = yaml.load(f, Loader=yaml.FullLoader) else: config = yaml.load(f) for k, v in config.items(): setattr(args, k, v) model = models.modules.__dict__[args.model['module']['arch']](args.model['module']) model = torch.nn.DataParallel(model) ckpt_path = exp_dir + '/checkpoints/ckpt_iter_{}.pth.tar'.format(args.iter) save_path = exp_dir + '/checkpoints/convert_iter_{}.pth.tar'.format(args.iter) ckpt = torch.load(ckpt_path) weight = ckpt['state_dict'] model.load_state_dict(weight, strict=True) model = model.module.image_encoder torch.save(model.state_dict(), save_path)
Example #7
Source File: utils.py From augur with GNU Affero General Public License v3.0 | 6 votes |
def read_config(fname): if not (fname and os.path.isfile(fname)): print("ERROR: config file %s not found."%fname) return defaultdict(dict) try: with open(fname, 'rb') as ifile: config = json.load(ifile) except json.decoder.JSONDecodeError as err: print("FATAL ERROR:") print("\tCouldn't parse the JSON file {}".format(fname)) print("\tError message: '{}'".format(err.msg)) print("\tLine number: '{}'".format(err.lineno)) print("\tColumn number: '{}'".format(err.colno)) print("\tYou must correct this file in order to proceed.") sys.exit(2) return config
Example #8
Source File: utils.py From augur with GNU Affero General Public License v3.0 | 6 votes |
def is_augur_version_compatable(version): """ Checks if the provided **version** is the same major version as the currently running version of augur. Parameters ---------- version : str version to check against the current version Returns ------- Bool """ current_version = packaging_version.parse(get_augur_version()) this_version = packaging_version.parse(version) return this_version.release[0] == current_version.release[0]
Example #9
Source File: bgperf.py From bgperf with Apache License 2.0 | 6 votes |
def doctor(args): ver = dckr.version()['Version'] if ver.endswith('-ce'): curr_version = version.parse(ver.replace('-ce', '')) else: curr_version = version.parse(ver) min_version = version.parse('1.9.0') ok = curr_version >= min_version print 'docker version ... {1} ({0})'.format(ver, 'ok' if ok else 'update to {} at least'.format(min_version)) print 'bgperf image', if img_exists('bgperf/exabgp'): print '... ok' else: print '... not found. run `bgperf prepare`' for name in ['gobgp', 'bird', 'quagga', 'frr']: print '{0} image'.format(name), if img_exists('bgperf/{0}'.format(name)): print '... ok' else: print '... not found. if you want to bench {0}, run `bgperf prepare`'.format(name) print '/proc/sys/net/ipv4/neigh/default/gc_thresh3 ... {0}'.format(gc_thresh3())
Example #10
Source File: ensemble.py From rasa_core with Apache License 2.0 | 6 votes |
def ensure_model_compatibility(metadata, version_to_check=None): from packaging import version if version_to_check is None: version_to_check = constants.MINIMUM_COMPATIBLE_VERSION model_version = metadata.get("rasa", "0.0.0") if version.parse(model_version) < version.parse(version_to_check): raise UnsupportedDialogueModelError( "The model version is to old to be " "loaded by this Rasa Core instance. " "Either retrain the model, or run with" "an older version. " "Model version: {} Instance version: {} " "Minimal compatible version: {}" "".format(model_version, rasa.__version__, version_to_check), model_version)
Example #11
Source File: database.py From lopocs with GNU Lesser General Public License v2.1 | 6 votes |
def create_pointcloud_lopocs_table(cls): ''' Create some meta tables that stores informations used by lopocs to stream patches in various formats This function uses "packaging.version.parse" to evaluate the current postgres version; depending on the system, it may returns verbose answers like "X.X.X (Ubuntu X.X-Xubuntu0.18.04.1)". One has to split this to keep only the simple version format. ''' # to_regclass function changed its signature in postgresql >= 9.6 full_server_version = cls.query('show server_version')[0][0] server_version = server_version_full.split()[0] # Keep only "X.X.X" if version.parse(server_version) < version.parse('9.6.0'): cls.execute(""" create or replace function to_regclass(text) returns regclass language sql as 'select to_regclass($1::cstring)' """) cls.execute(LOPOCS_TABLES_QUERY)
Example #12
Source File: project.py From signac with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _check_schema_compatibility(self): """Checks whether this project's data schema is compatible with this version. :raises RuntimeError: If the schema version is incompatible. """ schema_version = version.parse(SCHEMA_VERSION) config_schema_version = version.parse(self.config['schema_version']) if config_schema_version > schema_version: # Project config schema version is newer and therefore not supported. raise IncompatibleSchemaVersion( "The signac schema version used by this project is '{}', but signac {} " "only supports up to schema version '{}'. Try updating signac.".format( config_schema_version, __version__, schema_version)) elif config_schema_version < schema_version: raise IncompatibleSchemaVersion( "The signac schema version used by this project is '{}', but signac {} " "requires schema version '{}'. Please use '$ signac migrate' to " "irreversibly migrate this project's schema to the supported " "version.".format( config_schema_version, __version__, schema_version)) else: # identical and therefore compatible logger.debug( "The project's schema version {} is supported.".format( config_schema_version))
Example #13
Source File: utils.py From icme2019 with MIT License | 6 votes |
def check_version(version): """Return version of package on pypi.python.org using json.""" def check(version): try: url_pattern = 'https://pypi.python.org/pypi/mdeepctr/json' req = requests.get(url_pattern) latest_version = parse('0') version = parse(version) if req.status_code == requests.codes.ok: j = json.loads(req.text.encode('utf-8')) releases = j.get('releases', []) for release in releases: ver = parse(release) if not ver.is_prerelease: latest_version = max(latest_version, ver) if latest_version > version: logging.warning('\nDeepCTR version {0} detected. Your version is {1}.\nUse `pip install -U mdeepctr` to upgrade.Changelog: https://github.com/shenweichen/DeepCTR/releases/tag/v{0}'.format( latest_version, version)) except Exception: return Thread(target=check, args=(version,)).start()
Example #14
Source File: versions.py From addon-check with GNU General Public License v3.0 | 5 votes |
def __init__(self, version): self.version = parse(str(version).lower()) # non PEP440 compliant versions (legacy), for beta and alpha versions # convert them into PEP440 format: 1.1.0~beta01 -> 1.1.0beta01 if self._islegacy_devversion: self.version = Version(version.replace("~", ""))
Example #15
Source File: utils.py From stata_kernel with GNU General Public License v3.0 | 5 votes |
def check_stata_kernel_updated_version(stata_kernel_version): try: r = requests.get('https://pypi.org/pypi/stata-kernel/json') pypi_v = r.json()['info']['version'] if version.parse(pypi_v) > version.parse(stata_kernel_version): msg = """\ NOTE: A newer version of stata_kernel exists. Run \tpip install stata_kernel --upgrade to install the latest version. """ return dedent(msg) except requests.exceptions.RequestException: return
Example #16
Source File: helpers.py From micropy-cli with MIT License | 5 votes |
def iter_requirements(path): """Iterate requirements from a requirements.txt file. Args: path (str): path to file """ req_path = Path(path).absolute() with req_path.open('r') as rfile: for req in requirements.parse(rfile): yield req
Example #17
Source File: helpers.py From micropy-cli with MIT License | 5 votes |
def get_url_filename(url): """Parse filename from url. Args: url (str): url to parse Returns: str: filename of url """ path = requtil.urlparse(url).path file_name = Path(path).name return file_name
Example #18
Source File: tests.py From python-codicefiscale with MIT License | 5 votes |
def test_version(self): self.assertTrue(isinstance(version.parse(__version__), version.Version))
Example #19
Source File: fast5_info.py From ont_fast5_api with Mozilla Public License 2.0 | 5 votes |
def _legacy_version(self): legacy_cutoff = packaging_version.Version("1.1") return packaging_version.parse(str(self.version)) < legacy_cutoff
Example #20
Source File: px_generate_uorb_topic_files.py From px4_ros_com with BSD 3-Clause "New" or "Revised" License | 5 votes |
def generate_idl_file(filename_msg, msg_dir, alias, outputdir, templatedir, package, includepath, fastrtps_version, ros2_distro, ids): """ Generates an .idl from .msg file """ msg = os.path.join(msg_dir, filename_msg + ".msg") if (alias != ""): em_globals = get_em_globals( msg, alias, package, includepath, ids, fastrtps_version, ros2_distro, MsgScope.NONE) spec_short_name = alias else: em_globals = get_em_globals( msg, "", package, includepath, ids, fastrtps_version, ros2_distro, MsgScope.NONE) spec_short_name = em_globals["spec"].short_name # Make sure output directory exists: if not os.path.isdir(outputdir): os.makedirs(outputdir) template_file = os.path.join(templatedir, IDL_TEMPLATE_FILE) if version.parse(fastrtps_version) <= version.parse('1.7.2'): output_file = os.path.join(outputdir, IDL_TEMPLATE_FILE.replace( "msg.idl.em", str(spec_short_name + "_.idl"))) else: output_file = os.path.join(outputdir, IDL_TEMPLATE_FILE.replace( "msg.idl.em", str(spec_short_name + ".idl"))) return generate_by_template(output_file, template_file, em_globals)
Example #21
Source File: testing.py From ParlAI with MIT License | 5 votes |
def skipUnlessTorch14(testfn, reason='Test requires pytorch 1.4+'): skip = False if not TORCH_AVAILABLE: skip = True else: from packaging import version skip = version.parse(torch.__version__) < version.parse('1.4.0') return unittest.skipIf(skip, reason)(testfn)
Example #22
Source File: test_patch.py From git-pw with MIT License | 5 votes |
def test_update_with_invalid_state( self, mock_states, mock_show, mock_update): """Validate behavior with invalid state.""" mock_states.return_value = ['foo'] runner = CLIRunner() result = runner.invoke(patch.update_cmd, [ '123', '--state', 'bar']) assert result.exit_code == 2, result if version.parse(click.__version__) >= version.Version('7.1'): assert "Invalid value for '--state'" in result.output, result else: assert 'Invalid value for "--state"' in result.output, result
Example #23
Source File: shims.py From pipenv with MIT License | 5 votes |
def parse_version(cls, version): return parse_version(version)
Example #24
Source File: test_project.py From signac with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_project_schema_versions(self): impossibly_high_schema_version = '9999' assert version.parse(self.project.config['schema_version']) < \ version.parse(impossibly_high_schema_version) config = get_config(self.project.fn('signac.rc')) config['schema_version'] = impossibly_high_schema_version config.write() with pytest.raises(IncompatibleSchemaVersion): signac.init_project(name=str(self.project), root=self.project.root_directory())
Example #25
Source File: _utils.py From scanpy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def pkg_version(package): try: from importlib.metadata import version as v except ImportError: # < Python 3.8: Use backport module from importlib_metadata import version as v return version.parse(v(package))
Example #26
Source File: conftest.py From signac with BSD 3-Clause "New" or "Revised" License | 5 votes |
def deprecated_in_version(version_string): if version.parse(version_string) <= version.parse(signac.__version__): with pytest.deprecated_call(): yield else: yield
Example #27
Source File: _pypairs.py From scanpy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _check_import(): try: import pypairs except ImportError: raise ImportError('You need to install the package `pypairs`.') min_version = version.parse("3.0.9") if version.parse(pypairs.__version__) < min_version: raise ImportError(f'Please only use `pypairs` >= {min_version}')
Example #28
Source File: cli.py From changelogs with MIT License | 5 votes |
def main(): parser = argparse.ArgumentParser( description='bla' ) parser.add_argument("package", help="package name") parser.add_argument("vendor", help="vendor (pypi, npm, gem)", default="pypi", nargs='?') parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") parser.add_argument("-c", "--commits", help="", action="store_true") args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG) if args.commits: data, raw_log = changelogs.get_commit_log(args.package, vendor=args.vendor) else: data = changelogs.get(args.package, vendor=args.vendor) for release in sorted(data.keys(), key=lambda v: parse(v), reverse=True): print(release) print(data[release]) if not data and args.commits: print(raw_log)
Example #29
Source File: npm.py From changelogs with MIT License | 5 votes |
def get_releases(data, **kwargs): """ Gets all releases from pypi meta data. :param data: dict, meta data :return: list, str releases """ if "versions" in data: return sorted(data["versions"].keys(), key=lambda v: parse(v), reverse=True) return []
Example #30
Source File: pypi.py From changelogs with MIT License | 5 votes |
def get_releases(data, **kwargs): """ Gets all releases from pypi meta data. :param data: dict, meta data :return: list, str releases """ if "releases" in data: return sorted(data["releases"].keys(), key=lambda v: parse(v), reverse=True) return []