signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
def create_rpm(self, rpm_path): | return DebianRpm(rpm_path)<EOL> | Create Rpm object. | f1234:c10:m2 |
def create_installer(self, rpm_py_version, **kwargs): | return DebianInstaller(rpm_py_version, self.python, self.rpm, **kwargs)<EOL> | Create Installer object. | f1234:c10:m3 |
def __init__(self, python_path=sys.executable): | self.python_path = python_path<EOL> | Initialize this class. | f1234:c11:m0 |
def is_system_python(self): | return self.python_path.startswith('<STR_LIT>')<EOL> | Check if the Python is system Python. | f1234:c11:m1 |
@property<EOL><INDENT>def python_lib_dir(self):<DEDENT> | return self.python_lib_arch_dir<EOL> | site-packages directory. | f1234:c11:m2 |
@property<EOL><INDENT>def python_lib_arch_dir(self):<DEDENT> | return get_python_lib(plat_specific=True)<EOL> | Arch site-packages directory.
lib{64,32}/pythonN.N/site-packages | f1234:c11:m3 |
@property<EOL><INDENT>def python_lib_non_arch_dir(self):<DEDENT> | return get_python_lib()<EOL> | Non-arch site-packages directory.
lib/pythonN.N/site-packages | f1234:c11:m4 |
@property<EOL><INDENT>def python_lib_rpm_dir(self):<DEDENT> | return os.path.join(self.python_lib_dir, '<STR_LIT>')<EOL> | Installed directory of RPM Python binding. | f1234:c11:m5 |
@property<EOL><INDENT>def python_lib_rpm_dirs(self):<DEDENT> | libs = [self.python_lib_arch_dir, self.python_lib_non_arch_dir]<EOL>def append_rpm(path):<EOL><INDENT>return os.path.join(path, '<STR_LIT>')<EOL><DEDENT>return map(append_rpm, libs)<EOL> | Both arch and non-arch site-packages directories. | f1234:c11:m6 |
def is_python_binding_installed(self): | is_installed = False<EOL>is_install_error = False<EOL>try:<EOL><INDENT>is_installed = self.is_python_binding_installed_on_pip()<EOL><DEDENT>except InstallError:<EOL><INDENT>is_install_error = True<EOL><DEDENT>if not is_installed or is_install_error:<EOL><INDENT>for rpm_dir in self.python_lib_rpm_dirs:<EOL><INDENT>init_py = os.path.join(rpm_dir, '<STR_LIT>')<EOL>if os.path.isfile(init_py):<EOL><INDENT>is_installed = True<EOL>break<EOL><DEDENT><DEDENT><DEDENT>return is_installed<EOL> | Check if the Python binding has already installed.
Consider below cases.
- pip command is not installed.
- The installed RPM Python binding does not have information
showed as a result of pip list. | f1234:c11:m7 |
def is_python_binding_installed_on_pip(self): | pip_version = self._get_pip_version()<EOL>Log.debug('<STR_LIT>'.format(pip_version))<EOL>pip_major_version = int(pip_version.split('<STR_LIT:.>')[<NUM_LIT:0>])<EOL>installed = False<EOL>if pip_major_version >= <NUM_LIT:9>:<EOL><INDENT>json_obj = self._get_pip_list_json_obj()<EOL>for package in json_obj:<EOL><INDENT>Log.debug('<STR_LIT>'.format(package))<EOL>if package['<STR_LIT:name>'] in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>installed = True<EOL>Log.debug('<STR_LIT>'.format(<EOL>package['<STR_LIT:name>'], package['<STR_LIT:version>']))<EOL>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>lines = self._get_pip_list_lines()<EOL>for line in lines:<EOL><INDENT>if re.match('<STR_LIT>', line):<EOL><INDENT>installed = True<EOL>Log.debug('<STR_LIT>')<EOL>break<EOL><DEDENT><DEDENT><DEDENT>return installed<EOL> | Check if the Python binding has already installed. | f1234:c11:m8 |
def __init__(self, rpm_path, **kwargs): | is_file_checked = kwargs.get('<STR_LIT>', True)<EOL>if is_file_checked and not os.path.isfile(rpm_path):<EOL><INDENT>raise InstallError("<STR_LIT>".format(<EOL>rpm_path))<EOL><DEDENT>self.rpm_path = rpm_path<EOL>self.arch = Cmd.sh_e_out('<STR_LIT>').rstrip()<EOL>self._lib_dir = None<EOL> | Initialize this class. | f1234:c12:m0 |
@property<EOL><INDENT>def version(self):<DEDENT> | stdout = Cmd.sh_e_out('<STR_LIT>'.format(self.rpm_path))<EOL>rpm_version = stdout.split()[<NUM_LIT:2>]<EOL>return rpm_version<EOL> | RPM vesion string. | f1234:c12:m1 |
@property<EOL><INDENT>def version_info(self):<DEDENT> | version_str = self.version<EOL>return Utils.version_str2tuple(version_str)<EOL> | RPM version info. | f1234:c12:m2 |
def is_system_rpm(self): | sys_rpm_paths = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>]<EOL>matched = False<EOL>for sys_rpm_path in sys_rpm_paths:<EOL><INDENT>if self.rpm_path.startswith(sys_rpm_path):<EOL><INDENT>matched = True<EOL>break<EOL><DEDENT><DEDENT>return matched<EOL> | Check if the RPM is system RPM. | f1234:c12:m3 |
def has_set_up_py_in(self): | return (self.version_info >= (<NUM_LIT:4>, <NUM_LIT:10>))<EOL> | Check if the RPM source has setup.py.in. | f1234:c12:m4 |
def is_package_installed(self, package_name): | if not package_name:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>installed = True<EOL>try:<EOL><INDENT>Cmd.sh_e('<STR_LIT>'.format(self.rpm_path,<EOL>package_name))<EOL><DEDENT>except InstallError:<EOL><INDENT>installed = False<EOL><DEDENT>return installed<EOL> | Check if the RPM package is installed. | f1234:c12:m5 |
def verify_packages_installed(self, package_names): | if not package_names:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>missing_packages = []<EOL>for package_name in package_names:<EOL><INDENT>if not self.is_package_installed(package_name):<EOL><INDENT>missing_packages.append(package_name)<EOL><DEDENT><DEDENT>if missing_packages:<EOL><INDENT>comma_packages = '<STR_LIT:U+002CU+0020>'.join(missing_packages)<EOL>message = | Check if the RPM packages are installed.
Raise InstallError if any of the packages is not installed. | f1234:c12:m6 |
@property<EOL><INDENT>def lib_dir(self):<DEDENT> | raise NotImplementedError('<STR_LIT>')<EOL> | Return standard library directory path used by RPM libs. | f1234:c12:m7 |
@property<EOL><INDENT>def include_dir(self):<DEDENT> | return '<STR_LIT>'<EOL> | Return include directory.
TODO: Support non-system RPM. | f1234:c12:m8 |
def is_downloadable(self): | raise NotImplementedError('<STR_LIT>')<EOL> | Return if rpm is downloadable by the package command. | f1234:c12:m9 |
def __init__(self, rpm_path, **kwargs): | Rpm.__init__(self, rpm_path, **kwargs)<EOL>is_dnf = True if Cmd.which('<STR_LIT>') else False<EOL>self.is_dnf = is_dnf<EOL> | Initialize this class. | f1234:c13:m0 |
@property<EOL><INDENT>def lib_dir(self):<DEDENT> | if not self._lib_dir:<EOL><INDENT>rpm_lib_dir = None<EOL>cmd = '<STR_LIT>'.format(self.rpm_path)<EOL>out = Cmd.sh_e_out(cmd)<EOL>lines = out.split('<STR_LIT:\n>')<EOL>for line in lines:<EOL><INDENT>if '<STR_LIT>' in line:<EOL><INDENT>rpm_lib_dir = os.path.dirname(line)<EOL>break<EOL><DEDENT><DEDENT>self._lib_dir = rpm_lib_dir<EOL><DEDENT>return self._lib_dir<EOL> | Return standard library directory path used by RPM libs.
TODO: Support non-system RPM. | f1234:c13:m1 |
def has_composed_rpm_bulid_libs(self): | return self.version_info >= (<NUM_LIT:4>, <NUM_LIT:9>, <NUM_LIT:0>)<EOL> | Return if the sysmtem RPM has composed rpm-build-libs pacakage.
rpm-bulid-libs was created from rpm 4.9.0-0.beta1.1 on Fedora.
https://src.fedoraproject.org/rpms/rpm/blob/master/f/rpm.spec
> * 4.9.0-0.beta1.1
> - split librpmbuild and librpmsign to a separate rpm-build-libs
> package | f1234:c13:m2 |
@property<EOL><INDENT>def package_cmd(self):<DEDENT> | cmd = '<STR_LIT>' if self.is_dnf else '<STR_LIT>'<EOL>return cmd<EOL> | Return package command name. dnf/yum. | f1234:c13:m3 |
def is_downloadable(self): | is_plugin_avaiable = False<EOL>if self.is_dnf:<EOL><INDENT>is_plugin_avaiable = self.is_package_installed(<EOL>'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>"""<STR_LIT>"""<EOL>is_plugin_avaiable = self.is_package_installed(<EOL>'<STR_LIT>')<EOL><DEDENT>return is_plugin_avaiable<EOL> | Return if rpm is downloadable by the package command.
Check if dnf or yum plugin package exists. | f1234:c13:m4 |
def download_and_extract(self, package_name): | self.download(package_name)<EOL>self.extract(package_name)<EOL> | Download and extract given package. | f1234:c13:m5 |
def download(self, package_name): | if not package_name:<EOL><INDENT>ValueError('<STR_LIT>')<EOL><DEDENT>if self.is_dnf:<EOL><INDENT>cmd = '<STR_LIT>'.format(package_name, self.arch)<EOL><DEDENT>else:<EOL><INDENT>cmd = '<STR_LIT>'.format(package_name, self.arch)<EOL><DEDENT>try:<EOL><INDENT>Cmd.sh_e(cmd, stdout=subprocess.PIPE)<EOL><DEDENT>except CmdError as e:<EOL><INDENT>for out in (e.stdout, e.stderr):<EOL><INDENT>for line in out.split('<STR_LIT:\n>'):<EOL><INDENT>if re.match(r'<STR_LIT>', line) orre.match(r'<STR_LIT>', line):<EOL><INDENT>raise RemoteFileNotFoundError(<EOL>'<STR_LIT>'.format(<EOL>package_name<EOL>)<EOL>)<EOL><DEDENT><DEDENT><DEDENT>raise e<EOL><DEDENT> | Download given package. | f1234:c13:m6 |
def extract(self, package_name): | for cmd in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if not Cmd.which(cmd):<EOL><INDENT>message = '<STR_LIT>'.format(cmd)<EOL>raise InstallError(message)<EOL><DEDENT><DEDENT>pattern = '<STR_LIT>'.format(package_name, self.arch)<EOL>rpm_files = Cmd.find('<STR_LIT:.>', pattern)<EOL>if not rpm_files:<EOL><INDENT>raise InstallError('<STR_LIT>')<EOL><DEDENT>cmd = '<STR_LIT>'.format(rpm_files[<NUM_LIT:0>])<EOL>Cmd.sh_e(cmd)<EOL> | Extract given package. | f1234:c13:m7 |
def __init__(self, rpm_path, **kwargs): | Rpm.__init__(self, rpm_path, **kwargs)<EOL> | Initialize this class. | f1234:c14:m0 |
@property<EOL><INDENT>def lib_dir(self):<DEDENT> | if not self._lib_dir:<EOL><INDENT>lib_files = glob.glob("<STR_LIT>")<EOL>if not lib_files:<EOL><INDENT>raise InstallError("<STR_LIT>")<EOL><DEDENT>self._lib_dir = os.path.dirname(lib_files[<NUM_LIT:0>])<EOL><DEDENT>return self._lib_dir<EOL> | Return standard library directory path used by RPM libs. | f1234:c14:m1 |
def is_downloadable(self): | return False<EOL> | Return if rpm is downloadable by the package command.
Always return false. | f1234:c14:m2 |
def download_and_extract(self, package_name): | raise NotImplementedError('<STR_LIT>')<EOL> | Download and extract given package. | f1234:c14:m3 |
def download(self, package_name): | raise NotImplementedError('<STR_LIT>')<EOL> | Download given package. | f1234:c14:m4 |
def __init__(self, message): | InstallError.__init__(self, message)<EOL>self.stdout = None<EOL>self.sterr = None<EOL> | Initialize this class. | f1234:c17:m0 |
@classmethod<EOL><INDENT>def sh_e(cls, cmd, **kwargs):<DEDENT> | Log.debug('<STR_LIT>'.format(cmd))<EOL>cmd_kwargs = {<EOL>'<STR_LIT>': True,<EOL>}<EOL>cmd_kwargs.update(kwargs)<EOL>env = os.environ.copy()<EOL>env['<STR_LIT>'] = '<STR_LIT>'<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>env.update(kwargs['<STR_LIT>'])<EOL><DEDENT>cmd_kwargs['<STR_LIT>'] = env<EOL>cmd_kwargs['<STR_LIT>'] = subprocess.PIPE<EOL>proc = None<EOL>try:<EOL><INDENT>proc = subprocess.Popen(cmd, **cmd_kwargs)<EOL>stdout, stderr = proc.communicate()<EOL>returncode = proc.returncode<EOL>message_format = (<EOL>'<STR_LIT>'<EOL>)<EOL>Log.debug(message_format.format(returncode, stdout, stderr))<EOL>if stdout is not None:<EOL><INDENT>stdout = stdout.decode('<STR_LIT:utf-8>')<EOL><DEDENT>if stderr is not None:<EOL><INDENT>stderr = stderr.decode('<STR_LIT:utf-8>')<EOL><DEDENT>if returncode != <NUM_LIT:0>:<EOL><INDENT>message = '<STR_LIT>'.format(<EOL>cmd, returncode, os.getcwd())<EOL>if stderr is not None:<EOL><INDENT>message += '<STR_LIT>'.format(stderr)<EOL><DEDENT>ie = CmdError(message)<EOL>ie.stdout = stdout<EOL>ie.stderr = stderr<EOL>raise ie<EOL><DEDENT>return (stdout, stderr)<EOL><DEDENT>except Exception as e:<EOL><INDENT>try:<EOL><INDENT>proc.kill()<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>raise e<EOL><DEDENT> | Run the command. It behaves like "sh -e".
It raises InstallError if the command failed. | f1234:c20:m0 |
@classmethod<EOL><INDENT>def sh_e_out(cls, cmd, **kwargs):<DEDENT> | cmd_kwargs = {<EOL>'<STR_LIT>': subprocess.PIPE,<EOL>}<EOL>cmd_kwargs.update(kwargs)<EOL>return cls.sh_e(cmd, **cmd_kwargs)[<NUM_LIT:0>]<EOL> | Run the command. and returns the stdout. | f1234:c20:m1 |
@classmethod<EOL><INDENT>def cd(cls, directory):<DEDENT> | Log.debug('<STR_LIT>'.format(directory))<EOL>os.chdir(directory)<EOL> | Change directory. It behaves like "cd directory". | f1234:c20:m2 |
@classmethod<EOL><INDENT>@contextlib.contextmanager<EOL>def pushd(cls, new_dir):<DEDENT> | previous_dir = os.getcwd()<EOL>try:<EOL><INDENT>new_ab_dir = None<EOL>if os.path.isabs(new_dir):<EOL><INDENT>new_ab_dir = new_dir<EOL><DEDENT>else:<EOL><INDENT>new_ab_dir = os.path.join(previous_dir, new_dir)<EOL><DEDENT>cls.cd(new_ab_dir)<EOL>yield<EOL><DEDENT>finally:<EOL><INDENT>cls.cd(previous_dir)<EOL><DEDENT> | Change directory, and back to previous directory.
It behaves like "pushd directory; something; popd". | f1234:c20:m3 |
@classmethod<EOL><INDENT>def which(cls, cmd):<DEDENT> | abs_path_cmd = None<EOL>if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:3>):<EOL><INDENT>abs_path_cmd = shutil.which(cmd)<EOL><DEDENT>else:<EOL><INDENT>abs_path_cmd = find_executable(cmd)<EOL><DEDENT>return abs_path_cmd<EOL> | Return an absolute path of the command.
It behaves like "which command". | f1234:c20:m4 |
@classmethod<EOL><INDENT>def curl_remote_name(cls, file_url):<DEDENT> | tar_gz_file_name = file_url.split('<STR_LIT:/>')[-<NUM_LIT:1>]<EOL>if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:2>):<EOL><INDENT>from urllib.request import urlopen<EOL>from urllib.error import HTTPError<EOL><DEDENT>else:<EOL><INDENT>from urllib2 import urlopen<EOL>from urllib2 import HTTPError<EOL><DEDENT>response = None<EOL>try:<EOL><INDENT>response = urlopen(file_url)<EOL><DEDENT>except HTTPError as e:<EOL><INDENT>message = '<STR_LIT>'.format(<EOL>file_url, e)<EOL>if '<STR_LIT>' in str(e):<EOL><INDENT>raise RemoteFileNotFoundError(message)<EOL><DEDENT>else:<EOL><INDENT>raise InstallError(message)<EOL><DEDENT><DEDENT>tar_gz_file_obj = io.BytesIO(response.read())<EOL>with open(tar_gz_file_name, '<STR_LIT:wb>') as f_out:<EOL><INDENT>f_out.write(tar_gz_file_obj.read())<EOL><DEDENT>return tar_gz_file_name<EOL> | Download file_url, and save as a file name of the URL.
It behaves like "curl -O or --remote-name".
It raises HTTPError if the file_url not found. | f1234:c20:m5 |
@classmethod<EOL><INDENT>def tar_extract(cls, tar_comp_file_path):<DEDENT> | try:<EOL><INDENT>with contextlib.closing(tarfile.open(tar_comp_file_path)) as tar:<EOL><INDENT>tar.extractall()<EOL><DEDENT><DEDENT>except tarfile.ReadError as e:<EOL><INDENT>message_format = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL>raise InstallError(message_format.format(tar_comp_file_path, e))<EOL><DEDENT> | Extract tar.gz or tar bz2 file.
It behaves like
- tar xzf tar_gz_file_path
- tar xjf tar_bz2_file_path
It raises tarfile.ReadError if the file is broken. | f1234:c20:m6 |
@classmethod<EOL><INDENT>def find(cls, searched_dir, pattern):<DEDENT> | Log.debug('<STR_LIT>'.format(searched_dir, pattern))<EOL>matched_files = []<EOL>for root_dir, dir_names, file_names in os.walk(searched_dir,<EOL>followlinks=False):<EOL><INDENT>for file_name in file_names:<EOL><INDENT>if fnmatch.fnmatch(file_name, pattern):<EOL><INDENT>file_path = os.path.join(root_dir, file_name)<EOL>if not os.path.islink(file_path):<EOL><INDENT>matched_files.append(file_path)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>matched_files.sort()<EOL>return matched_files<EOL> | Find matched files.
It does not include symbolic file in the result. | f1234:c20:m7 |
@classmethod<EOL><INDENT>def mkdir_p(cls, path):<DEDENT> | os.makedirs(path)<EOL> | Make directory with recursively.
It behaves like "mkdir -p directory_path". | f1234:c20:m8 |
@classmethod<EOL><INDENT>def version_str2tuple(cls, version_str):<DEDENT> | if not isinstance(version_str, str):<EOL><INDENT>ValueError('<STR_LIT>')<EOL><DEDENT>version_info_list = re.findall(r'<STR_LIT>', version_str)<EOL>def convert_to_int(string):<EOL><INDENT>value = None<EOL>if re.match(r'<STR_LIT>', string):<EOL><INDENT>value = int(string)<EOL><DEDENT>else:<EOL><INDENT>value = string<EOL><DEDENT>return value<EOL><DEDENT>version_info_list = [convert_to_int(s) for s in version_info_list]<EOL>return tuple(version_info_list)<EOL> | Version info.
tuple object. ex. ('4', '14', '0', 'rc1') | f1234:c21:m0 |
@classmethod<EOL><INDENT>def error(cls, message):<DEDENT> | print('<STR_LIT>'.format(message))<EOL> | Log a message with level ERROR. | f1234:c22:m0 |
@classmethod<EOL><INDENT>def warn(cls, message):<DEDENT> | print('<STR_LIT>'.format(message))<EOL> | Log a message with level WARN. | f1234:c22:m1 |
@classmethod<EOL><INDENT>def info(cls, message):<DEDENT> | print('<STR_LIT>'.format(message))<EOL> | Log a message with level INFO. | f1234:c22:m2 |
@classmethod<EOL><INDENT>def debug(cls, message):<DEDENT> | if cls.verbose:<EOL><INDENT>print('<STR_LIT>'.format(message))<EOL><DEDENT> | Log a message with level DEBUG.
It does not log if verbose mode. | f1234:c22:m3 |
def install_rpm_py(): | python_path = sys.executable<EOL>cmd = '<STR_LIT>'.format(python_path)<EOL>exit_status = os.system(cmd)<EOL>if exit_status != <NUM_LIT:0>:<EOL><INDENT>raise Exception('<STR_LIT>'.format(cmd))<EOL><DEDENT> | Install RPM Python binding. | f1235:m0 |
def run(self): | install.run(self)<EOL>install_rpm_py()<EOL> | Run install process. | f1235:c0:m0 |
def run(self): | develop.run(self)<EOL>install_rpm_py()<EOL> | Run install process with development mode. | f1235:c1:m0 |
def run(self): | egg_info.run(self)<EOL>install_rpm_py()<EOL> | Run egg_info process. | f1235:c2:m0 |
def initialize_options(self): | pass<EOL> | Initilize options.
Just extend the super class's abstract method. | f1235:c3:m0 |
def finalize_options(self): | pass<EOL> | Finalize options.
Just extend the super class's abstract method. | f1235:c3:m1 |
def run(self): | raise Exception('<STR_LIT>')<EOL> | Run bdist_wheel process.
It raises error to make the method fail intentionally. | f1235:c3:m2 |
def get_setup_version(location, reponame, pkgname=None, archive_commit=None): | import warnings<EOL>pkgname = reponame if pkgname is None else pkgname<EOL>if archive_commit is None:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT>return Version.setup_version(os.path.dirname(os.path.abspath(location)),reponame,pkgname=pkgname,archive_commit=archive_commit)<EOL> | Helper for use in setup.py to get the current version from either
git describe or the .version file (if available).
Set pkgname to the package name if it is different from the
repository name.
To ensure git information is included in a git archive, add
setup.py to .gitattributes (in addition to __init__):
```
__init__.py export-subst
setup.py export-subst
```
Then supply "$Format:%h$" for archive_commit. | f1239:m1 |
def get_setupcfg_version(): | try:<EOL><INDENT>import configparser<EOL><DEDENT>except ImportError:<EOL><INDENT>import ConfigParser as configparser <EOL><DEDENT>import re<EOL>cfg = "<STR_LIT>"<EOL>autover_section = '<STR_LIT>'<EOL>config = configparser.ConfigParser()<EOL>config.read(cfg)<EOL>pkgname = config.get('<STR_LIT>','<STR_LIT:name>')<EOL>reponame = config.get(autover_section,'<STR_LIT>',vars={'<STR_LIT>':pkgname}) if autover_section in config.sections() else pkgname<EOL>archive_commit = None<EOL>archive_commit_key = autover_section+'<STR_LIT>'<EOL>for section in config.sections():<EOL><INDENT>if section.startswith(archive_commit_key):<EOL><INDENT>archive_commit = re.match(r"<STR_LIT>",section).group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>return get_setup_version(cfg,reponame=reponame,pkgname=pkgname,archive_commit=archive_commit)<EOL> | As get_setup_version(), but configure via setup.cfg.
If your project uses setup.cfg to configure setuptools, and hence has
at least a "name" key in the [metadata] section, you can
set the version as follows:
```
[metadata]
name = mypackage
version = attr: autover.version.get_setup_version2
```
If the repository name is different from the package name, specify
`reponame` as a [tool:autover] option:
```
[tool:autover]
reponame = mypackage
```
To ensure git information is included in a git archive, add
setup.cfg to .gitattributes (in addition to __init__):
```
__init__.py export-subst
setup.cfg export-subst
```
Then add the following to setup.cfg:
```
[tool:autover.configparser_workaround.archive_commit=$Format:%h$]
```
The above being a section heading rather than just a key is
because setuptools requires % to be escaped with %, or it can't
parse setup.cfg...but then git export-subst would not work. | f1239:m2 |
def __init__(self, release=None, fpath=None, commit=None, reponame=None,<EOL>commit_count_prefix='<STR_LIT>', archive_commit=None, **kwargs): | self.fpath = fpath<EOL>self._expected_commit = commit<EOL>if release is not None or '<STR_LIT>' in kwargs:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>self.expected_release = release<EOL>self._commit = None if (commit is None or commit.startswith("<STR_LIT>")) else commit<EOL>self._commit_count = None<EOL>self._release = None<EOL>self._dirty = False<EOL>self._prerelease = None<EOL>self.archive_commit= archive_commit<EOL>self.reponame = reponame<EOL>self.commit_count_prefix = commit_count_prefix<EOL> | :release: Release tuple (corresponding to the current VCS tag)
:commit Short SHA. Set to '$Format:%h$' for git archive support.
:fpath: Set to ``__file__`` to access version control information
:reponame: Used to verify VCS repository name. | f1239:c0:m1 |
@property<EOL><INDENT>def prerelease(self):<DEDENT> | return self.fetch()._prerelease<EOL> | Either None or one of 'aN' (alpha), 'bN' (beta) or 'rcN'
(release candidate) where N is an integer. | f1239:c0:m2 |
@property<EOL><INDENT>def release(self):<DEDENT> | return self.fetch()._release<EOL> | Return the release tuple | f1239:c0:m3 |
@property<EOL><INDENT>def commit(self):<DEDENT> | return self.fetch()._commit<EOL> | A specification for this particular VCS version, e.g. a short git SHA | f1239:c0:m4 |
@property<EOL><INDENT>def commit_count(self):<DEDENT> | return self.fetch()._commit_count<EOL> | Return the number of commits since the last release | f1239:c0:m5 |
@property<EOL><INDENT>def dirty(self):<DEDENT> | return self.fetch()._dirty<EOL> | True if there are uncommited changes, False otherwise | f1239:c0:m6 |
def fetch(self): | if self._release is not None:<EOL><INDENT>return self<EOL><DEDENT>self._release = self.expected_release<EOL>if not self.fpath:<EOL><INDENT>self._commit = self._expected_commit<EOL>return self<EOL><DEDENT>for cmd in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>try:<EOL><INDENT>self.git_fetch(cmd)<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return self<EOL> | Returns a tuple of the major version together with the
appropriate SHA and dirty bit (for development version only). | f1239:c0:m7 |
def _known_stale(self): | if self._output_from_file() is None:<EOL><INDENT>commit = None<EOL><DEDENT>else:<EOL><INDENT>commit = self.commit<EOL><DEDENT>known_stale = (self.archive_commit is not None<EOL>and not self.archive_commit.startswith('<STR_LIT>')<EOL>and self.archive_commit != commit)<EOL>if known_stale: self._commit_count = None<EOL>return known_stale<EOL> | The commit is known to be from a file (and therefore stale) if a
SHA is supplied by git archive and doesn't match the parsed commit. | f1239:c0:m9 |
def _output_from_file(self, entry='<STR_LIT>'): | try:<EOL><INDENT>vfile = os.path.join(os.path.dirname(self.fpath), '<STR_LIT>')<EOL>with open(vfile, '<STR_LIT:r>') as f:<EOL><INDENT>return json.loads(f.read()).get(entry, None)<EOL><DEDENT><DEDENT>except: <EOL><INDENT>return None<EOL><DEDENT> | Read the version from a .version file that may exist alongside __init__.py.
This file can be generated by piping the following output to file:
git describe --long --match v*.* | f1239:c0:m10 |
def _update_from_vcs(self, output): | split = output[<NUM_LIT:1>:].split('<STR_LIT:->')<EOL>dot_split = split[<NUM_LIT:0>].split('<STR_LIT:.>')<EOL>for prefix in ['<STR_LIT:a>','<STR_LIT:b>','<STR_LIT>']:<EOL><INDENT>if prefix in dot_split[-<NUM_LIT:1>]:<EOL><INDENT>prefix_split = dot_split[-<NUM_LIT:1>].split(prefix)<EOL>self._prerelease = prefix + prefix_split[-<NUM_LIT:1>]<EOL>dot_split[-<NUM_LIT:1>] = prefix_split[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>self._release = tuple(int(el) for el in dot_split)<EOL>self._commit_count = int(split[<NUM_LIT:1>])<EOL>self._commit = str(split[<NUM_LIT:2>][<NUM_LIT:1>:]) <EOL>self._dirty = (split[-<NUM_LIT:1>]=='<STR_LIT>')<EOL>return self<EOL> | Update state based on the VCS state e.g the output of git describe | f1239:c0:m11 |
def __str__(self): | known_stale = self._known_stale()<EOL>if self.release is None and not known_stale:<EOL><INDENT>extracted_directory_tag = self._output_from_file(entry='<STR_LIT>')<EOL>return '<STR_LIT:None>' if extracted_directory_tag is None else extracted_directory_tag<EOL><DEDENT>elif self.release is None and known_stale:<EOL><INDENT>extracted_directory_tag = self._output_from_file(entry='<STR_LIT>')<EOL>if extracted_directory_tag is not None:<EOL><INDENT>return extracted_directory_tag<EOL><DEDENT>return '<STR_LIT>'.format(SHA=self.archive_commit)<EOL><DEDENT>release = '<STR_LIT:.>'.join(str(el) for el in self.release)<EOL>prerelease = '<STR_LIT>' if self.prerelease is None else self.prerelease<EOL>if self.commit_count == <NUM_LIT:0> and not self.dirty:<EOL><INDENT>return release + prerelease<EOL><DEDENT>commit = self.commit<EOL>dirty = '<STR_LIT>' if self.dirty else '<STR_LIT>'<EOL>archive_commit = '<STR_LIT>'<EOL>if known_stale:<EOL><INDENT>archive_commit = '<STR_LIT>'<EOL>commit = self.archive_commit<EOL><DEDENT>if archive_commit != '<STR_LIT>':<EOL><INDENT>postcount = self.commit_count_prefix + '<STR_LIT:0>'<EOL><DEDENT>elif self.commit_count not in [<NUM_LIT:0>, None]:<EOL><INDENT>postcount = self.commit_count_prefix + str(self.commit_count)<EOL><DEDENT>else:<EOL><INDENT>postcount = '<STR_LIT>'<EOL><DEDENT>components = [release, prerelease, postcount,<EOL>'<STR_LIT>' if commit is None else '<STR_LIT>' + commit, dirty,<EOL>archive_commit]<EOL>return '<STR_LIT>'.join(components)<EOL> | Version in x.y.z string format. Does not include the "v"
prefix of the VCS version tags, for pip compatibility.
If the commit count is non-zero or the repository is dirty,
the string representation is equivalent to the output of::
git describe --long --match v*.* --dirty
(with "v" prefix removed). | f1239:c0:m12 |
def abbrev(self): | return '<STR_LIT:.>'.join(str(el) for el in self.release)<EOL> | Abbreviated string representation of just the release number. | f1239:c0:m14 |
def verify(self, string_version=None): | if string_version and string_version != str(self):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if self.dirty:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if self.expected_release is not None and self.release != self.expected_release:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if self.commit_count !=<NUM_LIT:0>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if (self._expected_commit is not None<EOL>and not self._expected_commit.startswith( "<STR_LIT>")):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT> | Check that the version information is consistent with the VCS
before doing a release. If supplied with a string version,
this is also checked against the current version. Should be
called from setup.py with the declared package version before
releasing to PyPI. | f1239:c0:m15 |
@classmethod<EOL><INDENT>def get_setup_version(cls, setup_path, reponame, describe=False,<EOL>dirty='<STR_LIT>', pkgname=None, archive_commit=None):<DEDENT> | pkgname = reponame if pkgname is None else pkgname<EOL>policies = ['<STR_LIT>','<STR_LIT>', '<STR_LIT>']<EOL>if dirty not in policies:<EOL><INDENT>raise AssertionError("<STR_LIT>" % policies)<EOL><DEDENT>fpath = os.path.join(setup_path, pkgname, "<STR_LIT>")<EOL>version = Version(fpath=fpath, reponame=reponame, archive_commit=archive_commit)<EOL>if describe:<EOL><INDENT>vstring = version.git_fetch(as_string=True)<EOL><DEDENT>else:<EOL><INDENT>vstring = str(version)<EOL><DEDENT>if version.dirty and dirty == '<STR_LIT>':<EOL><INDENT>raise AssertionError('<STR_LIT>')<EOL><DEDENT>elif version.dirty and dirty=='<STR_LIT>':<EOL><INDENT>return vstring.replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return vstring<EOL><DEDENT> | Helper for use in setup.py to get the version from the .version file (if available)
or more up-to-date information from git describe (if available).
Assumes the __init__.py will be found in the directory
{reponame}/__init__.py relative to setup.py unless pkgname is
explicitly specified in which case that name is used instead.
If describe is True, the raw string obtained from git described is
returned which is useful for updating the .version file.
The dirty policy can be one of 'report', 'strip', 'raise'. If it is
'report' the version string may end in '-dirty' if the repository is
in a dirty state. If the policy is 'strip', the '-dirty' suffix
will be stripped out if present. If the policy is 'raise', an
exception is raised if the repository is in a dirty state. This can
be useful if you want to make sure packages are not built from a
dirty repository state. | f1239:c0:m16 |
def __init__(self, release=None, fpath=None, commit=None,<EOL>reponame=None, dev=None, commit_count=<NUM_LIT:0>): | self.fpath = fpath<EOL>self._expected_commit = commit<EOL>self.expected_release = release<EOL>self._commit = None if commit in [None, "<STR_LIT>"] else commit<EOL>self._commit_count = commit_count<EOL>self._release = None<EOL>self._dirty = False<EOL>self.reponame = reponame<EOL>self.dev = dev<EOL> | :release: Release tuple (corresponding to the current VCS tag)
:commit Short SHA. Set to '$Format:%h$' for git archive support.
:fpath: Set to ``__file__`` to access version control information
:reponame: Used to verify VCS repository name.
:dev: Development version number. None if not a development version.
:commit_count Commits since last release. Set for dev releases. | f1239:c1:m0 |
@property<EOL><INDENT>def release(self):<DEDENT> | return self.fetch()._release<EOL> | Return the release tuple | f1239:c1:m1 |
@property<EOL><INDENT>def commit(self):<DEDENT> | return self.fetch()._commit<EOL> | A specification for this particular VCS version, e.g. a short git SHA | f1239:c1:m2 |
@property<EOL><INDENT>def commit_count(self):<DEDENT> | return self.fetch()._commit_count<EOL> | Return the number of commits since the last release | f1239:c1:m3 |
@property<EOL><INDENT>def dirty(self):<DEDENT> | return self.fetch()._dirty<EOL> | True if there are uncommited changes, False otherwise | f1239:c1:m4 |
def fetch(self): | if self._release is not None:<EOL><INDENT>return self<EOL><DEDENT>self._release = self.expected_release<EOL>if not self.fpath:<EOL><INDENT>self._commit = self._expected_commit<EOL>return self<EOL><DEDENT>for cmd in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>try:<EOL><INDENT>self.git_fetch(cmd)<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return self<EOL> | Returns a tuple of the major version together with the
appropriate SHA and dirty bit (for development version only). | f1239:c1:m5 |
def _update_from_vcs(self, output): | split = output[<NUM_LIT:1>:].split('<STR_LIT:->')<EOL>if '<STR_LIT>' in split[<NUM_LIT:0>]:<EOL><INDENT>dev_split = split[<NUM_LIT:0>].split('<STR_LIT>')<EOL>self.dev = int(dev_split[<NUM_LIT:1>])<EOL>split[<NUM_LIT:0>] = dev_split[<NUM_LIT:0>]<EOL>if split[<NUM_LIT:0>].endswith('<STR_LIT:.>'):<EOL><INDENT>split[<NUM_LIT:0>] = dev_split[<NUM_LIT:0>][:-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>self._release = tuple(int(el) for el in split[<NUM_LIT:0>].split('<STR_LIT:.>'))<EOL>self._commit_count = int(split[<NUM_LIT:1>])<EOL>self._commit = str(split[<NUM_LIT:2>][<NUM_LIT:1>:]) <EOL>self._dirty = (split[-<NUM_LIT:1>]=='<STR_LIT>')<EOL>return self<EOL> | Update state based on the VCS state e.g the output of git describe | f1239:c1:m7 |
def __str__(self): | if self.release is None: return '<STR_LIT:None>'<EOL>release = '<STR_LIT:.>'.join(str(el) for el in self.release)<EOL>release = '<STR_LIT>' % (release, self.dev) if self.dev is not None else release<EOL>if (self._expected_commit is not None) and ("<STR_LIT>" not in self._expected_commit):<EOL><INDENT>pass <EOL><DEDENT>elif (self.commit_count == <NUM_LIT:0> and not self.dirty):<EOL><INDENT>return release<EOL><DEDENT>dirty_status = '<STR_LIT>' if self.dirty else '<STR_LIT>'<EOL>return '<STR_LIT>' % (release, self.commit_count if self.commit_count else '<STR_LIT:x>',<EOL>self.commit, dirty_status)<EOL> | Version in x.y.z string format. Does not include the "v"
prefix of the VCS version tags, for pip compatibility.
If the commit count is non-zero or the repository is dirty,
the string representation is equivalent to the output of::
git describe --long --match v*.* --dirty
(with "v" prefix removed). | f1239:c1:m8 |
def abbrev(self,dev_suffix="<STR_LIT>"): | return '<STR_LIT:.>'.join(str(el) for el in self.release) +(dev_suffix if self.commit_count > <NUM_LIT:0> or self.dirty else "<STR_LIT>")<EOL> | Abbreviated string representation, optionally declaring whether it is
a development version. | f1239:c1:m10 |
def __eq__(self, other): | if self.dirty or other.dirty: return False<EOL>return ((self.release, self.commit_count, self.dev)<EOL>== (other.release, other.commit_count, other.dev))<EOL> | Two versions are considered equivalent if and only if they are
from the same release, with the same commit count, and are not
dirty. Any dirty version is considered different from any
other version, since it could potentially have any arbitrary
changes even for the same release and commit count. | f1239:c1:m11 |
def verify(self, string_version=None): | if string_version and string_version != str(self):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if self.dirty:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if self.release != self.expected_release:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if self.commit_count !=<NUM_LIT:0>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if self._expected_commit not in [None, "<STR_LIT>"]:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT> | Check that the version information is consistent with the VCS
before doing a release. If supplied with a string version,
this is also checked against the current version. Should be
called from setup.py with the declared package version before
releasing to PyPI. | f1239:c1:m14 |
@contextmanager<EOL>def logging_level(level): | level = level.upper()<EOL>levels = [DEBUG, INFO, WARNING, ERROR, CRITICAL, VERBOSE]<EOL>level_names = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if level not in level_names:<EOL><INDENT>raise Exception("<STR_LIT>" % (level, levels))<EOL><DEDENT>param_logger = get_logger()<EOL>logging_level = param_logger.getEffectiveLevel()<EOL>param_logger.setLevel(levels[level_names.index(level)])<EOL>try:<EOL><INDENT>yield None<EOL><DEDENT>finally:<EOL><INDENT>param_logger.setLevel(logging_level)<EOL><DEDENT> | Temporarily modify param's logging level. | f1240:m1 |
@contextmanager<EOL>def batch_watch(parameterized, run=True): | BATCH_WATCH = parameterized.param._BATCH_WATCH<EOL>parameterized.param._BATCH_WATCH = True<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>parameterized.param._BATCH_WATCH = BATCH_WATCH<EOL>if run and not BATCH_WATCH:<EOL><INDENT>parameterized.param._batch_call_watchers()<EOL><DEDENT><DEDENT> | Context manager to batch watcher events on a parameterized object.
The context manager will queue any events triggered by setting a
parameter on the supplied parameterized object and dispatch them
all at once when the context manager exits. If run=False the
queued events are not dispatched and should be processed manually. | f1240:m2 |
def classlist(class_): | return inspect.getmro(class_)[::-<NUM_LIT:1>]<EOL> | Return a list of the class hierarchy above (and including) the given class.
Same as inspect.getmro(class_)[::-1] | f1240:m3 |
def descendents(class_): | assert isinstance(class_,type)<EOL>q = [class_]<EOL>out = []<EOL>while len(q):<EOL><INDENT>x = q.pop(<NUM_LIT:0>)<EOL>out.insert(<NUM_LIT:0>,x)<EOL>for b in x.__subclasses__():<EOL><INDENT>if b not in q and b not in out:<EOL><INDENT>q.append(b)<EOL><DEDENT><DEDENT><DEDENT>return out[::-<NUM_LIT:1>]<EOL> | Return a list of the class hierarchy below (and including) the given class.
The list is ordered from least- to most-specific. Can be useful for
printing the contents of an entire class hierarchy. | f1240:m4 |
def get_all_slots(class_): | <EOL>all_slots = []<EOL>parent_param_classes = [c for c in classlist(class_)[<NUM_LIT:1>::]]<EOL>for c in parent_param_classes:<EOL><INDENT>if hasattr(c,'<STR_LIT>'):<EOL><INDENT>all_slots+=c.__slots__<EOL><DEDENT><DEDENT>return all_slots<EOL> | Return a list of slot names for slots defined in class_ and its
superclasses. | f1240:m5 |
def get_occupied_slots(instance): | return [slot for slot in get_all_slots(type(instance))<EOL>if hasattr(instance,slot)]<EOL> | Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.) | f1240:m6 |
def all_equal(arg1,arg2): | if all(hasattr(el, '<STR_LIT>') for el in [arg1,arg2]):<EOL><INDENT>return arg1==arg2<EOL><DEDENT>try:<EOL><INDENT>return all(a1 == a2 for a1, a2 in zip(arg1, arg2))<EOL><DEDENT>except TypeError:<EOL><INDENT>return arg1==arg2<EOL><DEDENT> | Return a single boolean for arg1==arg2, even for numpy arrays
using element-wise comparison.
Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.
If both objects have an '_infinitely_iterable' attribute, they are
not be zipped together and are compared directly instead. | f1240:m7 |
def add_metaclass(metaclass): | def wrapper(cls):<EOL><INDENT>orig_vars = cls.__dict__.copy()<EOL>orig_vars.pop('<STR_LIT>', None)<EOL>orig_vars.pop('<STR_LIT>', None)<EOL>for slots_var in orig_vars.get('<STR_LIT>', ()):<EOL><INDENT>orig_vars.pop(slots_var)<EOL><DEDENT>return metaclass(cls.__name__, cls.__bases__, orig_vars)<EOL><DEDENT>return wrapper<EOL> | Class decorator for creating a class with a metaclass. | f1240:m8 |
def no_instance_params(cls): | cls._disable_instance__params = True<EOL>return cls<EOL> | Disables instance parameters on the class | f1240:m11 |
@accept_arguments<EOL>def depends(func, *dependencies, **kw): | <EOL>watch = kw.pop("<STR_LIT>",False)<EOL>assert len(kw)==<NUM_LIT:0>, "<STR_LIT>"<EOL>_dinfo = getattr(func, '<STR_LIT>', {})<EOL>_dinfo.update({'<STR_LIT>': dependencies,<EOL>'<STR_LIT>': watch})<EOL>@wraps(func)<EOL>def _depends(*args,**kw):<EOL><INDENT>return func(*args,**kw)<EOL><DEDENT>_depends._dinfo = _dinfo<EOL>return _depends<EOL> | Annotates a Parameterized method to express its dependencies.
The specified dependencies can be either be Parameters of this
class, or Parameters of subobjects (Parameterized objects that
are values of this object's parameters). Dependencies can either
be on Parameter values, or on other metadata about the Parameter. | f1240:m13 |
@accept_arguments<EOL>def output(func, *output, **kw): | if output:<EOL><INDENT>outputs = []<EOL>for i, out in enumerate(output):<EOL><INDENT>i = i if len(output) > <NUM_LIT:1> else None<EOL>if isinstance(out, tuple) and len(out) == <NUM_LIT:2> and isinstance(out[<NUM_LIT:0>], str):<EOL><INDENT>outputs.append(out+(i,))<EOL><DEDENT>elif isinstance(out, str):<EOL><INDENT>outputs.append((out, Parameter(), i))<EOL><DEDENT>else:<EOL><INDENT>outputs.append((None, out, i))<EOL><DEDENT><DEDENT><DEDENT>elif kw:<EOL><INDENT>py_major = sys.version_info.major<EOL>py_minor = sys.version_info.minor<EOL>if (py_major < <NUM_LIT:3> or (py_major == <NUM_LIT:3> and py_minor < <NUM_LIT:6>)) and len(kw) > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>outputs = [(name, otype, i if len(kw) > <NUM_LIT:1> else None)<EOL>for i, (name, otype) in enumerate(kw.items())]<EOL><DEDENT>else:<EOL><INDENT>outputs = [(None, Parameter(), None)]<EOL><DEDENT>names, processed = [], []<EOL>for name, otype, i in outputs:<EOL><INDENT>if isinstance(otype, type):<EOL><INDENT>if issubclass(otype, Parameter):<EOL><INDENT>otype = otype()<EOL><DEDENT>else:<EOL><INDENT>from .import ClassSelector<EOL>otype = ClassSelector(class_=otype)<EOL><DEDENT><DEDENT>elif isinstance(otype, tuple) and all(isinstance(t, type) for t in otype):<EOL><INDENT>from .import ClassSelector<EOL>otype = ClassSelector(class_=otype)<EOL><DEDENT>if not isinstance(otype, Parameter):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>processed.append((name, otype, i))<EOL>names.append(name)<EOL><DEDENT>if len(set(names)) != len(names):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>_dinfo = getattr(func, '<STR_LIT>', {})<EOL>_dinfo.update({'<STR_LIT>': processed})<EOL>@wraps(func)<EOL>def _output(*args,**kw):<EOL><INDENT>return func(*args,**kw)<EOL><DEDENT>_output._dinfo = _dinfo<EOL>return _output<EOL> | output allows annotating a method on a Parameterized class to
declare that it returns an output of a specific type. The outputs
of a Parameterized class can be queried using the
Parameterized.param.outputs method. By default the output will
inherit the method name but a custom name can be declared by
expressing the Parameter type using a keyword argument. Declaring
multiple return types using keywords is only supported in Python >= 3.6.
The simplest declaration simply declares the method returns an
object without any type guarantees, e.g.:
@output()
If a specific parameter type is specified this is a declaration
that the method will return a value of that type, e.g.:
@output(param.Number())
To override the default name of the output the type may be declared
as a keyword argument, e.g.:
@output(custom_name=param.Number())
Multiple outputs may be declared using keywords mapping from
output name to the type for Python >= 3.6 or using tuples of the
same format, which is supported for earlier versions, i.e. these
two declarations are equivalent:
@output(number=param.Number(), string=param.String())
@output(('number', param.Number()), ('string', param.String()))
output also accepts Python object types which will be upgraded to
a ClassSelector, e.g.:
@output(int) | f1240:m14 |
def as_uninitialized(fn): | @wraps(fn)<EOL>def override_initialization(self_,*args,**kw):<EOL><INDENT>parameterized_instance = self_.self<EOL>original_initialized=parameterized_instance.initialized<EOL>parameterized_instance.initialized=False<EOL>fn(parameterized_instance,*args,**kw)<EOL>parameterized_instance.initialized=original_initialized<EOL><DEDENT>return override_initialization<EOL> | Decorator: call fn with the parameterized_instance's
initialization flag set to False, then revert the flag.
(Used to decorate Parameterized methods that must alter
a constant Parameter.) | f1240:m17 |
def script_repr(val,imports,prefix,settings): | return pprint(val,imports,prefix,settings,unknown_value=None,<EOL>qualify=True,separator="<STR_LIT:\n>")<EOL> | Variant of repr() designed for generating a runnable script.
Instances of types that require special handling can use the
script_repr_reg dictionary. Using the type as a key, add a
function that returns a suitable representation of instances of
that type, and adds the required import statement.
The repr of a parameter can be suppressed by returning None from
the appropriate hook in script_repr_reg. | f1240:m18 |
def pprint(val,imports, prefix="<STR_LIT>", settings=[],<EOL>unknown_value='<STR_LIT>', qualify=False, separator='<STR_LIT>'): | <EOL>if isinstance(val,type):<EOL><INDENT>rep = type_script_repr(val,imports,prefix,settings)<EOL><DEDENT>elif type(val) in script_repr_reg:<EOL><INDENT>rep = script_repr_reg[type(val)](val,imports,prefix,settings)<EOL><DEDENT>elif hasattr(val,'<STR_LIT>'):<EOL><INDENT>rep=val.script_repr(imports, prefix+"<STR_LIT:U+0020>")<EOL><DEDENT>elif hasattr(val,'<STR_LIT>'):<EOL><INDENT>rep=val.pprint(imports=imports, prefix=prefix+"<STR_LIT:U+0020>",<EOL>qualify=qualify, unknown_value=unknown_value,<EOL>separator=separator)<EOL><DEDENT>else:<EOL><INDENT>rep=repr(val)<EOL><DEDENT>return rep<EOL> | (Experimental) Pretty printed representation of a parameterized
object that may be evaluated with eval.
Similar to repr except introspection of the constructor (__init__)
ensures a valid and succinct representation is generated.
Only parameters are represented (whether specified as standard,
positional, or keyword arguments). Parameters specified as
positional arguments are always shown, followed by modified
parameters specified as keyword arguments, sorted by precedence.
unknown_value determines what to do where a representation cannot be
generated for something required to recreate the object. Such things
include non-parameter positional and keyword arguments, and certain
values of parameters (e.g. some random state objects).
Supplying an unknown_value of None causes unrepresentable things
to be silently ignored. If unknown_value is a string, that
string will appear in place of any unrepresentable things. If
unknown_value is False, an Exception will be raised if an
unrepresentable value is encountered.
If supplied, imports should be a list, and it will be populated
with the set of imports required for the object and all of its
parameter values.
If qualify is True, the class's path will be included (e.g. "a.b.C()"),
otherwise only the class will appear ("C()").
Parameters will be separated by a comma only by default, but the
separator parameter allows an additional separator to be supplied
(e.g. a newline could be supplied to have each Parameter appear on a
separate line).
NOTE: pprint will replace script_repr in a future version of
param, but is not yet a complete replacement for script_repr. | f1240:m19 |
def print_all_param_defaults(): | print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>classes = descendents(Parameterized)<EOL>classes.sort(key=lambda x:x.__name__)<EOL>for c in classes:<EOL><INDENT>c.print_param_defaults()<EOL><DEDENT>print("<STR_LIT>")<EOL> | Print the default values for all imported Parameters. | f1240:m24 |
def __init__(self,default=None,doc=None,label=None,precedence=None, <EOL>instantiate=False,constant=False,readonly=False,<EOL>pickle_default_value=True, allow_None=False,<EOL>per_instance=True): | self.name = None<EOL>self._internal_name = None<EOL>self.owner = None<EOL>self._label = label<EOL>self.precedence = precedence<EOL>self.default = default<EOL>self.doc = doc<EOL>self.constant = constant or readonly <EOL>self.readonly = readonly<EOL>self._set_instantiate(instantiate)<EOL>self.pickle_default_value = pickle_default_value<EOL>self.allow_None = (default is None or allow_None)<EOL>self.watchers = {}<EOL>self.per_instance = per_instance<EOL> | Initialize a new Parameter object: store the supplied attributes.
default: the owning class's value for the attribute
represented by this Parameter.
precedence is a value, usually in the range 0.0 to 1.0, that
allows the order of Parameters in a class to be defined (for
e.g. in GUI menus). A negative precedence indicates a
parameter that should be hidden in e.g. GUI menus.
default, doc, and precedence default to None. This is to allow
inheritance of Parameter slots (attributes) from the owning-class'
class hierarchy (see ParameterizedMetaclass).
per_instance defaults to True and controls whether a new
Parameter instance can be created for every Parameterized
instance. If False, all instances of a Parameterized class
will share the same parameter object, including all validation
attributes.
In rare cases where the default value should not be pickled,
set pickle_default_value=False (e.g. for file search paths). | f1240:c2:m0 |
def _set_instantiate(self,instantiate): | <EOL>if self.readonly:<EOL><INDENT>self.instantiate = False<EOL><DEDENT>else:<EOL><INDENT>self.instantiate = instantiate or self.constant<EOL><DEDENT> | Constant parameters must be instantiated. | f1240:c2:m3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.