Python packaging.version.Version() Examples
The following are 30
code examples of packaging.version.Version().
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: dialect.py From sqlalchemy-redshift with MIT License | 6 votes |
def _fetch_redshift_column_attributes(self, column): text = "" if sa_version >= Version('1.3.0'): info = column.dialect_options['redshift'] else: if not hasattr(column, 'info'): return text info = column.info identity = info.get('identity') if identity: text += " IDENTITY({0},{1})".format(identity[0], identity[1]) encode = info.get('encode') if encode: text += " ENCODE " + encode distkey = info.get('distkey') if distkey: text += " DISTKEY" sortkey = info.get('sortkey') if sortkey: text += " SORTKEY" return text
Example #2
Source File: reporter_demo.py From resolvelib with ISC License | 6 votes |
def read_spec(lines): candidates = {} latest = None for line in lines: if not line or line.startswith("#"): continue if not line.startswith(" "): name, version = splitstrip(line, 2) version = Version(version) latest = Candidate(name, version) candidates[latest] = set() else: if latest is None: raise RuntimeError( "Spec has dependencies before first candidate" ) name, specifier = splitstrip(line, 2) specifier = SpecifierSet(specifier) candidates[latest].add(Requirement(name, specifier)) return candidates
Example #3
Source File: __init__.py From pytest with MIT License | 6 votes |
def _checkversion(self) -> None: import pytest minver = self.inicfg.get("minversion", None) if minver: # Imported lazily to improve start-up time. from packaging.version import Version if not isinstance(minver, str): raise pytest.UsageError( "%s: 'minversion' must be a single value" % self.inifile ) if Version(minver) > Version(pytest.__version__): raise pytest.UsageError( "%s: 'minversion' requires pytest-%s, actual pytest-%s'" % (self.inifile, minver, pytest.__version__,) )
Example #4
Source File: python.py From pythonfinder with MIT License | 6 votes |
def update_metadata(self, metadata): # type: (Dict[str, Union[str, int, Version]]) -> None """ Update the metadata on the current :class:`pythonfinder.models.python.PythonVersion` Given a parsed version dictionary from :func:`pythonfinder.utils.parse_python_version`, update the instance variables of the current version instance to reflect the newly supplied values. """ for key in metadata: try: _ = getattr(self, key) except AttributeError: continue else: setattr(self, key, metadata[key])
Example #5
Source File: python.py From pythonfinder with MIT License | 6 votes |
def parse(cls, version): # type: (str) -> Dict[str, Union[str, int, Version]] """ Parse a valid version string into a dictionary Raises: ValueError -- Unable to parse version string ValueError -- Not a valid python version TypeError -- NoneType or unparseable type passed in :param str version: A valid version string :return: A dictionary with metadata about the specified python version. :rtype: dict """ if version is None: raise TypeError("Must pass a value to parse!") version_dict = parse_python_version(str(version)) if not version_dict: raise ValueError("Not a valid python version: %r" % version) return version_dict
Example #6
Source File: plugin_system.py From ros2cli with Apache License 2.0 | 6 votes |
def satisfies_version(version, caret_range): assert caret_range.startswith('^'), 'Only supports caret ranges' extension_point_version = Version(version) extension_version = Version(caret_range[1:]) next_extension_version = get_upper_bound_caret_version( extension_version) if extension_point_version < extension_version: raise PluginException( 'Extension point is too old (%s), the extension requires ' "'%s'" % (extension_point_version, extension_version)) if extension_point_version >= next_extension_version: raise PluginException( 'Extension point is newer (%s), than what the extension ' "supports '%s'" % (extension_point_version, extension_version))
Example #7
Source File: _io.py From starfish with MIT License | 6 votes |
def read_versioned_binary_mask( file_obj: BinaryIO, ) -> bm.BinaryMaskCollection: with tarfile.open(mode="r|gz", fileobj=file_obj) as tf: if tf.pax_headers is None: raise ValueError( f"file does not appear to be a binary mask file (does not have headers)") if tf.pax_headers.get(AttrKeys.DOCTYPE, None) != DOCTYPE_STRING: raise ValueError( f"file does not appear to be a binary mask file (missing or incorrect doctype)") if AttrKeys.VERSION not in tf.pax_headers: raise ValueError(f"file missing version data") requested_version = Version(tf.pax_headers[AttrKeys.VERSION]) for version, implementation in BinaryMaskIO.ASCENDING_VERSIONS: if version == requested_version: return implementation().read_binary_mask(tf) else: raise ValueError(f"No reader for version {requested_version}")
Example #8
Source File: _io.py From starfish with MIT License | 6 votes |
def write_versioned_binary_mask( file_obj: BinaryIO, binary_mask: bm.BinaryMaskCollection, requested_version: Optional[Version] = None, ): if requested_version is None: implementation = BinaryMaskIO.ASCENDING_VERSIONS[-1][1] else: for version, implementing_class in BinaryMaskIO.ASCENDING_VERSIONS: if version == requested_version: implementation = implementing_class break else: raise ValueError(f"No writer for version {requested_version}") implementation().write_binary_mask(file_obj, binary_mask)
Example #9
Source File: dialect.py From sqlalchemy-redshift with MIT License | 6 votes |
def _get_column_info(self, *args, **kwargs): kw = kwargs.copy() encode = kw.pop('encode', None) if sa_version < Version('1.2.0'): # SQLAlchemy 1.2.0 introduced the 'comment' param del kw['comment'] if sa_version >= Version('1.3.16'): # SQLAlchemy 1.3.16 introduced generated columns, # not supported in redshift kw['generated'] = '' column_info = super(RedshiftDialect, self)._get_column_info( *args, **kw ) if isinstance(column_info['type'], VARCHAR): if column_info['type'].length is None: column_info['type'] = NullType() if 'info' not in column_info: column_info['info'] = {} if encode and encode != 'none': column_info['info']['encode'] = encode return column_info
Example #10
Source File: test_python.py From pythonfinder with MIT License | 6 votes |
def test_python_versions(monkeypatch, special_character_python): def mock_version(*args, **kwargs): version_output = "2.7.15+ (default, Jun 28 2018, 13:15:42)\n[GCC 7.2.0]" class FakeObj(object): def __init__(self, out): self.out = out def communicate(self): return self.out, "" def kill(self): pass c = FakeObj(version_output.split()[0]) return c os.environ["PYTHONFINDER_IGNORE_UNSUPPORTED"] = str("1") with monkeypatch.context() as m: m.setattr("subprocess.Popen", mock_version) parsed = pythonfinder.models.python.PythonVersion.from_path( special_character_python.strpath ) assert isinstance(parsed.version, Version)
Example #11
Source File: python.py From pipenv with MIT License | 6 votes |
def parse(cls, version): # type: (str) -> Dict[str, Union[str, int, Version]] """ Parse a valid version string into a dictionary Raises: ValueError -- Unable to parse version string ValueError -- Not a valid python version TypeError -- NoneType or unparseable type passed in :param str version: A valid version string :return: A dictionary with metadata about the specified python version. :rtype: dict """ if version is None: raise TypeError("Must pass a value to parse!") version_dict = parse_python_version(str(version)) if not version_dict: raise ValueError("Not a valid python version: %r" % version) return version_dict
Example #12
Source File: test_fortiosapi_virsh.py From fortiosapi with Apache License 2.0 | 6 votes |
def test_01logout_login(self): # This test if we properly regenerate the CSRF from the cookie when not restarting the program # can include changing login/vdom passwd on the same session # Check the license validity/force a license update and wait in license call.. if Version(fgt.get_version()) > Version('5.6'): try: self.assertTrue(fgt.license()['results']['vm']['status'] == "vm_valid" or "vm_eval") except KeyError: time.sleep(35) else: self.assertTrue(True, "not supported before 5.6") time.sleep(35) # do a logout then login again # TODO a expcetion check self.assertEqual(fgt.logout(), None) self.test_00login()
Example #13
Source File: python.py From pipenv with MIT License | 6 votes |
def update_metadata(self, metadata): # type: (Dict[str, Union[str, int, Version]]) -> None """ Update the metadata on the current :class:`pythonfinder.models.python.PythonVersion` Given a parsed version dictionary from :func:`pythonfinder.utils.parse_python_version`, update the instance variables of the current version instance to reflect the newly supplied values. """ for key in metadata: try: _ = getattr(self, key) except AttributeError: continue else: setattr(self, key, metadata[key])
Example #14
Source File: notify.py From tox with MIT License | 6 votes |
def get_last_release_versions(repo: Repo) -> Tuple[Version, Version]: print("get latest release version") commit_to_tag = {tag.commit.hexsha: tag for tag in repo.tags} _, release_tag = sorted( [(tag.commit.committed_datetime, tag) for tag in repo.tags], reverse=True, )[0] for commit in release_tag.commit.iter_parents(): if commit.hexsha in commit_to_tag: prev_release_tag = commit_to_tag[commit.hexsha] prev_version = Version(prev_release_tag.name) if not any( ( prev_version.is_devrelease, prev_version.is_prerelease, prev_version.is_postrelease, ), ): break else: raise RuntimeError("no previous release") release_version = Version(release_tag.name) print(f"\trelease {release_version} with previous {prev_version}") return prev_version, release_version
Example #15
Source File: transaction_service.py From safe-relay-service with MIT License | 6 votes |
def estimate_tx(self, safe_address: str, to: str, value: int, data: str, operation: int, gas_token: Optional[str]) -> TransactionEstimationWithNonce: """ :return: TransactionEstimation with costs and last used nonce of safe :raises: InvalidGasToken: If Gas Token is not valid """ if not self._is_valid_gas_token(gas_token): raise InvalidGasToken(gas_token) last_used_nonce = self.get_last_used_nonce(safe_address) safe = Safe(safe_address, self.ethereum_client) safe_tx_gas = safe.estimate_tx_gas(to, value, data, operation) safe_tx_base_gas = safe.estimate_tx_base_gas(to, value, data, operation, gas_token, safe_tx_gas) # For Safe contracts v1.0.0 operational gas is not used (`base_gas` has all the related costs already) safe_version = safe.retrieve_version() if Version(safe_version) >= Version('1.0.0'): safe_tx_operational_gas = 0 else: safe_tx_operational_gas = safe.estimate_tx_operational_gas(len(data) if data else 0) # Can throw RelayServiceException gas_price = self._estimate_tx_gas_price(gas_token) return TransactionEstimationWithNonce(safe_tx_gas, safe_tx_base_gas, safe_tx_base_gas, safe_tx_operational_gas, gas_price, gas_token or NULL_ADDRESS, last_used_nonce)
Example #16
Source File: lists.py From shavar with Mozilla Public License 2.0 | 5 votes |
def add_versioned_lists_to_registry( settings, serving, ver_lists, type_, list_name, shavar_prod_lists_branches ): for branch in shavar_prod_lists_branches: branch_name = branch.get('name') ver = version.parse(branch_name) if isinstance(ver, version.Version): original_path, versioned_path = get_original_and_versioned_paths( settings['source'] ) # change config to reflect version branches versioned_source = settings['source'].replace( original_path, versioned_path.format(branch_name)) settings['source'] = versioned_source # get new list for the version list_ = create_list(type_, list_name, settings) try: list_._source.load() except NoDataError: err_msg = ( 'Skipping {0} version support for {1} ' 'since the file does not exist in S3' ) logger.error(err_msg.format(ver, list_name)) original_source = settings['source'].replace( versioned_path.format(branch_name), original_path) settings['source'] = original_source continue versioned_list_name = get_versioned_list_name( branch_name, list_name) serving[versioned_list_name] = list_ ver_lists[list_name].append(branch_name) # revert settings original_source = settings['source'].replace( versioned_path.format(branch_name), original_path) settings['source'] = original_source
Example #17
Source File: test_plot.py From scprep with GNU General Public License v3.0 | 5 votes |
def test_generate_colorbar_dict(): if Version(matplotlib.__version__) >= Version("3.2"): errtype = ValueError msg = "is not a valid value for name; supported values are" else: errtype = TypeError msg = "unhashable type: 'dict'" utils.assert_raises_message( errtype, msg, scprep.plot.tools.generate_colorbar, cmap={"+": "r", "-": "b"}, )
Example #18
Source File: base.py From agents-aea with Apache License 2.0 | 5 votes |
def _parse_aea_version_specifier(self, aea_version_specifiers: str) -> SpecifierSet: try: Version(aea_version_specifiers) return SpecifierSet("==" + aea_version_specifiers) except packaging.version.InvalidVersion: pass return SpecifierSet(aea_version_specifiers)
Example #19
Source File: base.py From agents-aea with Apache License 2.0 | 5 votes |
def _check_aea_version(package_configuration: PackageConfiguration): """Check the package configuration version against the version of the framework.""" current_aea_version = Version(aea.__version__) version_specifiers = package_configuration.aea_version_specifiers if current_aea_version not in version_specifiers: raise ValueError( "The CLI version is {}, but package {} requires version {}".format( current_aea_version, package_configuration.public_id, package_configuration.aea_version_specifiers, ) )
Example #20
Source File: _io.py From starfish with MIT License | 5 votes |
def __init_subclass__(cls, version_descriptor: Version, **kwargs): super.__init_subclass__(**kwargs) # type: ignore cls.VERSION = version_descriptor BinaryMaskIO.ASCENDING_VERSIONS.append((version_descriptor, cls)) BinaryMaskIO.ASCENDING_VERSIONS.sort()
Example #21
Source File: lists.py From shavar with Mozilla Public License 2.0 | 5 votes |
def match_with_versioned_list(app_version, supported_versions, list_name): ver = version.parse(app_version) # need to be wary of ESR, it's considered legacy version in packaging if not isinstance(ver, version.Version) or not supported_versions: return list_name, None default_ver = version.parse(OLDEST_SUPPORTED_VERSION) is_default_version = ( ver.release and ver.release[0] <= default_ver.release[0]) if is_default_version: return (get_versioned_list_name(default_ver.public, list_name), default_ver.public) if ver.public in supported_versions: return get_versioned_list_name(ver.public, list_name), ver.public # truncate version to be less specific to lazy match truncate_ind = -1 while len(app_version) != abs(truncate_ind): if app_version[:truncate_ind] in supported_versions: versioned_list_name = get_versioned_list_name( app_version[:truncate_ind], list_name) return versioned_list_name, app_version[:truncate_ind] truncate_ind -= 1 # get the major version and match to that major_ver = str(float(ver.release[0])) if major_ver in supported_versions: versioned_list_name = get_versioned_list_name(major_ver, list_name) return versioned_list_name, major_ver # if none of the supported versions match, match with master return list_name, None
Example #22
Source File: test_deployments.py From controller with MIT License | 5 votes |
def test_bad_init_api_version(self): data = "1.13+" with self.assertRaises( InvalidVersion, msg='packaging.version.InvalidVersion: Invalid version: {}'.format(data) # noqa ): Version('{}'.format(data))
Example #23
Source File: poet.py From poet with MIT License | 5 votes |
def normalized_version(self): """ Return a PEP 440 compatible version. :rtype: str """ return str(PackageVersion(self._version))
Example #24
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 #25
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 #26
Source File: pypi_wheel_provider.py From resolvelib with ISC License | 5 votes |
def get_project_from_pypi(project, extras): """Return candidates created from the project name and extras.""" url = "https://pypi.org/simple/{}".format(project) data = requests.get(url).content doc = html5lib.parse(data, namespaceHTMLElements=False) for i in doc.findall(".//a"): url = i.attrib["href"] py_req = i.attrib.get("data-requires-python") # Skip items that need a different Python version if py_req: spec = SpecifierSet(py_req) if PYTHON_VERSION not in spec: continue path = urlparse(url).path filename = path.rpartition("/")[-1] # We only handle wheels if not filename.endswith(".whl"): continue # TODO: Handle compatibility tags? # Very primitive wheel filename parsing name, version = filename[:-4].split("-")[:2] try: version = Version(version) except InvalidVersion: # Ignore files with invalid versions continue yield Candidate(name, version, url=url, extras=extras)
Example #27
Source File: __init__.py From pytest with MIT License | 5 votes |
def _validate_plugins(self) -> None: required_plugins = sorted(self.getini("required_plugins")) if not required_plugins: return # Imported lazily to improve start-up time. from packaging.version import Version from packaging.requirements import InvalidRequirement, Requirement plugin_info = self.pluginmanager.list_plugin_distinfo() plugin_dist_info = {dist.project_name: dist.version for _, dist in plugin_info} missing_plugins = [] for required_plugin in required_plugins: spec = None try: spec = Requirement(required_plugin) except InvalidRequirement: missing_plugins.append(required_plugin) continue if spec.name not in plugin_dist_info: missing_plugins.append(required_plugin) elif Version(plugin_dist_info[spec.name]) not in spec.specifier: missing_plugins.append(required_plugin) if missing_plugins: fail( "Missing required plugins: {}".format(", ".join(missing_plugins)), pytrace=False, )
Example #28
Source File: test_metadata.py From PandasSchema with GNU General Public License v3.0 | 5 votes |
def test_version(self): """ Check that we have a __version__ defined, and that it's at least 0.3.0 """ self.assertIsNotNone(pandas_schema.__version__) parsed = version.parse(pandas_schema.__version__) self.assertGreaterEqual(parsed, version.Version('0.3.0'))
Example #29
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 #30
Source File: python.py From pipenv with MIT License | 5 votes |
def as_dict(self): # type: () -> Dict[str, Union[int, bool, Version, None]] return { "major": self.major, "minor": self.minor, "patch": self.patch, "is_prerelease": self.is_prerelease, "is_postrelease": self.is_postrelease, "is_devrelease": self.is_devrelease, "is_debug": self.is_debug, "version": self.version, "company": self.company, }