pax_global_header00006660000000000000000000000064135647332600014523gustar00rootroot0000000000000052 comment=455789d17b93124720f3fe584495e71d57f871af python-asteval-0.9.17/000077500000000000000000000000001356473326000145775ustar00rootroot00000000000000python-asteval-0.9.17/.gitattributes000066400000000000000000000000411356473326000174650ustar00rootroot00000000000000asteval/_version.py export-subst python-asteval-0.9.17/.gitignore000066400000000000000000000001231356473326000165630ustar00rootroot00000000000000*.pyc *~ *# .coverage NonGit/ doc/_build doc/*.pdf build dist *.egg-info MANIFEST python-asteval-0.9.17/.travis.yml000066400000000000000000000017501356473326000167130ustar00rootroot00000000000000# Config file for automatic testing at travis-ci.org language: python sudo: false python: - 2.7 - 3.5 - 3.6 - 3.7 - 3.8 env: - version=without_numpy - version=with_numpy before_install: - wget https://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh -O miniconda.sh - bash miniconda.sh -b -p $HOME/miniconda - export PATH="$HOME/miniconda/bin:$PATH" - hash -r - conda config --set always_yes yes --set changeps1 no - conda update -q conda - conda info -a install: - conda create -q -n test_env python=$TRAVIS_PYTHON_VERSION pytest coverage - source activate test_env - if [[ $version == with_numpy ]]; then conda install numpy ; fi - python setup.py install - pip install codecov script: - cd tests - pytest - if [[ $version == with_numpy ]]; then coverage run --source=asteval test_asteval.py && coverage report -m ; fi after_success: - if [[ $version == with_numpy ]]; then codecov ; fi python-asteval-0.9.17/INSTALL000066400000000000000000000005701356473326000156320ustar00rootroot00000000000000Installation instructions for asteval ======================================== To install the asteval module, use:: python setup.py install or pip install asteval Asteval require Python 2.7 or Python 3.4 or higher. If installed, many functions and constants from numpy will be used by default. Matt Newville Last Update: 28-Oct-2017 python-asteval-0.9.17/LICENSE000066400000000000000000000021201356473326000155770ustar00rootroot00000000000000The MIT License Copyright (c) 2019 Matthew Newville, The University of Chicago Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-asteval-0.9.17/MANIFEST.in000066400000000000000000000004661356473326000163430ustar00rootroot00000000000000include README.txt INSTALL LICENSE MANIFEST.in PKG-INFO include setup.py publish_docs.sh exclude *.pyc core.* *~ *.pdf recursive-include lib *.py recursive-include tests *.py recursive-include doc * recursive-exclude doc/_build * recursive-exclude doc *.pdf include versioneer.py include asteval/_version.py python-asteval-0.9.17/README.rst000066400000000000000000000044311356473326000162700ustar00rootroot00000000000000ASTEVAL ======= .. image:: https://travis-ci.org/newville/asteval.png :target: https://travis-ci.org/newville/asteval .. image:: https://codecov.io/gh/newville/asteval/branch/master/graph/badge.svg :target: https://codecov.io/gh/newville/asteval .. image:: https://zenodo.org/badge/4185/newville/asteval.svg :target: https://zenodo.org/badge/latestdoi/4185/newville/asteval Links ----- * Documentation: http://newville.github.com/asteval * PyPI installation: http://pypi.python.org/pypi/asteval * Development Code: http://github.com/newville/asteval * Issue Tracker: http://github.com/newville/asteval/issues What is it? ----------- ASTEVAL is a safe(ish) evaluator of Python expressions and statements, using Python's ast module. The idea is to provide a simple, safe, and robust miniature mathematical language that can handle user-input. The emphasis here is on mathematical expressions, and so many functions from ``numpy`` are imported and used if available. Many Python lanquage constructs are supported by default, These include slicing, subscripting, list comprehension, conditionals (if-elif-else blocks and if expressions), flow control (for loops, while loops, and try-except-finally blocks). All data are python objects, and built-in data structures (dictionaries, tuple, lists, numpy arrays, strings) are fully supported by default. Many of the standard builtin python functions are available, as are all mathemetical functions from the math module. If the numpy module is installed, many of its functions will also be available. Users can define and run their own functions within the confines of the limitations of asteval. There are several absences and differences with Python, and asteval is by no means an attempt to reproduce Python with its own ast module. Some of the most important differences and absences are: 1. Variable and function symbol names are held in a simple symbol table (a single dictionary), giving a flat namespace. 2. creating classes is not supported. 3. importing modules is not supported. 4. function decorators, yield, lambda, exec, and eval are not supported. 5. files can only be opened in read-only mode. In addition, accessing many internal methods and classes of objects is forbidden in order to strengthen asteval against malicious user code. python-asteval-0.9.17/asteval/000077500000000000000000000000001356473326000162365ustar00rootroot00000000000000python-asteval-0.9.17/asteval/__init__.py000066400000000000000000000017511356473326000203530ustar00rootroot00000000000000""" ASTEVAL provides a numpy-aware, safe(ish) "eval" function Emphasis is on mathematical expressions, and so numpy ufuncs are used if available. Symbols are held in the Interpreter symbol table 'symtable': a simple dictionary supporting a simple, flat namespace. Expressions can be compiled into ast node for later evaluation, using the values in the symbol table current at evaluation time. version: 0.9.13 last update: 2018-Sept-29 License: MIT Author: Matthew Newville Center for Advanced Radiation Sources, The University of Chicago """ from .asteval import Interpreter from .astutils import (NameFinder, valid_symbol_name, make_symbol_table, get_ast_names, check_pyversion) from ._version import get_versions __all__ = ['Interpreter', 'NameFinder', 'valid_symbol_name', 'make_symbol_table', 'get_ast_names'] __version__ = get_versions()['version'] del get_versions python-asteval-0.9.17/asteval/_version.py000066400000000000000000000441011356473326000204340ustar00rootroot00000000000000 # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = " (tag: 0.9.17)" git_full = "e298284ed4778307c6e8145647eddf9bb17f752e" git_date = "2019-11-14 14:59:30 -0600" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "asteval-" cfg.versionfile_source = "asteval/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} python-asteval-0.9.17/asteval/asteval.py000066400000000000000000001051661356473326000202600ustar00rootroot00000000000000#!/usr/bin/env python """Safe(ish) evaluation of mathematical expression using Python's ast module. This module provides an Interpreter class that compiles a restricted set of Python expressions and statements to Python's AST representation, and then executes that representation using values held in a symbol table. The symbol table is a simple dictionary, giving a simple, flat namespace. This comes pre-loaded with many functions from Python's builtin and math module. If numpy is installed, many numpy functions are also included. Additional symbols can be added when an Interpreter is created, but the user of that interpreter will not be able to import additional modules. Expressions, including loops, conditionals, and function definitions can be compiled into ast node and then evaluated later, using the current values in the symbol table. The result is a restricted, simplified version of Python meant for numerical caclulations that is somewhat safer than 'eval' because many unsafe operations (such as 'import' and 'eval') are simply not allowed. Many parts of Python syntax are supported, including: for loops, while loops, if-then-elif-else conditionals try-except (including 'finally') function definitions with def advanced slicing: a[::-1], array[-3:, :, ::2] if-expressions: out = one_thing if TEST else other list comprehension out = [sqrt(i) for i in values] The following Python syntax elements are not supported: Import, Exec, Lambda, Class, Global, Generators, Yield, Decorators In addition, while many builtin functions are supported, several builtin functions that are considered unsafe are missing ('eval', 'exec', and 'getattr' for example) """ from __future__ import division, print_function import ast import time import inspect from sys import exc_info, stdout, stderr, version_info from .astutils import (UNSAFE_ATTRS, HAS_NUMPY, make_symbol_table, numpy, op2func, ExceptionHolder, ReturnedNone, valid_symbol_name, check_pyversion) builtins = __builtins__ if not isinstance(builtins, dict): builtins = builtins.__dict__ ALL_NODES = ['arg', 'assert', 'assign', 'attribute', 'augassign', 'binop', 'boolop', 'break', 'call', 'compare', 'continue', 'delete', 'dict', 'ellipsis', 'excepthandler', 'expr', 'extslice', 'for', 'functiondef', 'if', 'ifexp', 'index', 'interrupt', 'list', 'listcomp', 'module', 'name', 'nameconstant', 'num', 'pass', 'print', 'raise', 'repr', 'return', 'slice', 'str', 'subscript', 'try', 'tuple', 'unaryop', 'while', 'constant'] PY3 = check_pyversion() class Interpreter(object): """create an asteval Interpreter: a restricted, simplified interpreter of mathematical expressions using Python syntax. Parameters ---------- symtable : dict or `None` dictionary to use as symbol table (if `None`, one will be created). usersyms : dict or `None` dictionary of user-defined symbols to add to symbol table. writer : file-like or `None` callable file-like object where standard output will be sent. err_writer : file-like or `None` callable file-like object where standard error will be sent. use_numpy : bool whether to use functions from numpy. minimal : bool create a minimal interpreter: disable all options (see Note 1). no_if : bool whether to support `if` blocks no_for : bool whether to support `for` blocks. no_while : bool whether to support `while` blocks. no_try : bool whether to support `try` blocks. no_functiondef : bool whether to support user-defined functions. no_ifexp : bool whether to support if expressions. no_listcomp : bool whether to support list comprehension. no_augassign : bool whether to support augemented assigments (`a += 1`, etc). no_assert : bool whether to support `assert`. no_delete : bool whether to support `del`. no_raise : bool whether to support `raise`. no_print : bool whether to support `print`. readonly_symbols : iterable or `None` symbols that the user can not assign to builtins_readonly : bool whether to blacklist all symbols that are in the initial symtable Notes ----- 1. setting `minimal=True` is equivalent to setting all `no_***` options to `True`. """ def __init__(self, symtable=None, usersyms=None, writer=None, err_writer=None, use_numpy=True, minimal=False, no_if=False, no_for=False, no_while=False, no_try=False, no_functiondef=False, no_ifexp=False, no_listcomp=False, no_augassign=False, no_assert=False, no_delete=False, no_raise=False, no_print=False, max_time=None, readonly_symbols=None, builtins_readonly=False): self.writer = writer or stdout self.err_writer = err_writer or stderr if symtable is None: if usersyms is None: usersyms = {} symtable = make_symbol_table(use_numpy=use_numpy, **usersyms) if no_print: symtable['print'] = self._nullprinter else: symtable['print'] = self._printer self.symtable = symtable self._interrupt = None self.error = [] self.error_msg = None self.expr = None self.retval = None self.lineno = 0 self.start_time = time.time() self.use_numpy = HAS_NUMPY and use_numpy nodes = ALL_NODES[:] if minimal or no_if: nodes.remove('if') if minimal or no_for: nodes.remove('for') if minimal or no_while: nodes.remove('while') if minimal or no_try: nodes.remove('try') if minimal or no_functiondef: nodes.remove('functiondef') if minimal or no_ifexp: nodes.remove('ifexp') if minimal or no_assert: nodes.remove('assert') if minimal or no_delete: nodes.remove('delete') if minimal or no_raise: nodes.remove('raise') if minimal or no_print: nodes.remove('print') if minimal or no_listcomp: nodes.remove('listcomp') if minimal or no_augassign: nodes.remove('augassign') self.node_handlers = {} for node in nodes: self.node_handlers[node] = getattr(self, "on_%s" % node) # to rationalize try/except try/finally for Python2.6 through Python3.3 if 'try' in self.node_handlers: self.node_handlers['tryexcept'] = self.node_handlers['try'] self.node_handlers['tryfinally'] = self.node_handlers['try'] if readonly_symbols is None: self.readonly_symbols = set() else: self.readonly_symbols = set(readonly_symbols) if builtins_readonly: self.readonly_symbols |= set(self.symtable) self.no_deepcopy = [key for key, val in symtable.items() if (callable(val) or 'numpy.lib.index_tricks' in repr(val) or inspect.ismodule(val))] def remove_nodehandler(self, node): """remove support for a node returns current node handler, so that it might be re-added with add_nodehandler() """ out = None if node in self.node_handlers: out = self.node_handlers.pop(node) return out def set_nodehandler(self, node, handler): """set node handler""" self.node_handlers[node] = handler def user_defined_symbols(self): """Return a set of symbols that have been added to symtable after construction. I.e., the symbols from self.symtable that are not in self.no_deepcopy. Returns ------- unique_symbols : set symbols in symtable that are not in self.no_deepcopy """ sym_in_current = set(self.symtable.keys()) sym_from_construction = set(self.no_deepcopy) unique_symbols = sym_in_current.difference(sym_from_construction) return unique_symbols def unimplemented(self, node): """Unimplemented nodes.""" self.raise_exception(node, exc=NotImplementedError, msg="'%s' not supported" % (node.__class__.__name__)) def raise_exception(self, node, exc=None, msg='', expr=None, lineno=None): """Add an exception.""" if self.error is None: self.error = [] if expr is None: expr = self.expr if len(self.error) > 0 and not isinstance(node, ast.Module): msg = '%s' % msg err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno) self._interrupt = ast.Break() self.error.append(err) if self.error_msg is None: self.error_msg = "at expr='%s'" % (self.expr) elif len(msg) > 0: self.error_msg = msg if exc is None: try: exc = self.error[0].exc except: exc = RuntimeError raise exc(self.error_msg) # main entry point for Ast node evaluation # parse: text of statements -> ast # run: ast -> result # eval: string statement -> result = run(parse(statement)) def parse(self, text): """Parse statement/expression to Ast representation.""" self.expr = text try: out = ast.parse(text) except SyntaxError: self.raise_exception(None, msg='Syntax Error', expr=text) except: self.raise_exception(None, msg='Runtime Error', expr=text) return out def run(self, node, expr=None, lineno=None, with_raise=True): """Execute parsed Ast representation for an expression.""" # Note: keep the 'node is None' test: internal code here may run # run(None) and expect a None in return. out = None if len(self.error) > 0: return out if node is None: return out if isinstance(node, str): node = self.parse(node) if lineno is not None: self.lineno = lineno if expr is not None: self.expr = expr # get handler for this node: # on_xxx with handle nodes of type 'xxx', etc try: handler = self.node_handlers[node.__class__.__name__.lower()] except KeyError: return self.unimplemented(node) # run the handler: this will likely generate # recursive calls into this run method. try: ret = handler(node) if isinstance(ret, enumerate): ret = list(ret) return ret except: if with_raise: if len(self.error) == 0: # Unhandled exception that didn't go through raise_exception self.raise_exception(node, expr=expr) raise def __call__(self, expr, **kw): """Call class instance as function.""" return self.eval(expr, **kw) def eval(self, expr, lineno=0, show_errors=True): """Evaluate a single statement.""" self.lineno = lineno self.error = [] self.start_time = time.time() try: node = self.parse(expr) except: errmsg = exc_info()[1] if len(self.error) > 0: errmsg = "\n".join(self.error[0].get_error()) if not show_errors: try: exc = self.error[0].exc except: exc = RuntimeError raise exc(errmsg) print(errmsg, file=self.err_writer) return try: return self.run(node, expr=expr, lineno=lineno) except: errmsg = exc_info()[1] if len(self.error) > 0: errmsg = "\n".join(self.error[0].get_error()) if not show_errors: try: exc = self.error[0].exc except: exc = RuntimeError raise exc(errmsg) print(errmsg, file=self.err_writer) return @staticmethod def dump(node, **kw): """Simple ast dumper.""" return ast.dump(node, **kw) # handlers for ast components def on_expr(self, node): """Expression.""" return self.run(node.value) # ('value',) def on_index(self, node): """Index.""" return self.run(node.value) # ('value',) def on_return(self, node): # ('value',) """Return statement: look for None, return special sentinal.""" self.retval = self.run(node.value) if self.retval is None: self.retval = ReturnedNone return def on_repr(self, node): """Repr.""" return repr(self.run(node.value)) # ('value',) def on_module(self, node): # ():('body',) """Module def.""" out = None for tnode in node.body: out = self.run(tnode) return out def on_expression(self, node): "basic expression" return self.on_module(node) # ():('body',) def on_pass(self, node): """Pass statement.""" return None # () def on_ellipsis(self, node): """Ellipses.""" return Ellipsis # for break and continue: set the instance variable _interrupt def on_interrupt(self, node): # () """Interrupt handler.""" self._interrupt = node return node def on_break(self, node): """Break.""" return self.on_interrupt(node) def on_continue(self, node): """Continue.""" return self.on_interrupt(node) def on_assert(self, node): # ('test', 'msg') """Assert statement.""" if not self.run(node.test): self.raise_exception(node, exc=AssertionError, msg=node.msg) return True def on_list(self, node): # ('elt', 'ctx') """List.""" return [self.run(e) for e in node.elts] def on_tuple(self, node): # ('elts', 'ctx') """Tuple.""" return tuple(self.on_list(node)) def on_dict(self, node): # ('keys', 'values') """Dictionary.""" return dict([(self.run(k), self.run(v)) for k, v in zip(node.keys, node.values)]) def on_constant(self, node): # ('value', 'kind') """Return constant value.""" return node.value def on_num(self, node): # ('n',) """Return number.""" return node.n def on_str(self, node): # ('s',) """Return string.""" return node.s def on_nameconstant(self, node): # ('value',) """named constant""" return node.value def on_name(self, node): # ('id', 'ctx') """Name node.""" ctx = node.ctx.__class__ if ctx in (ast.Param, ast.Del): return str(node.id) else: if node.id in self.symtable: return self.symtable[node.id] else: msg = "name '%s' is not defined" % node.id self.raise_exception(node, exc=NameError, msg=msg) def on_nameconstant(self, node): """ True, False, None in python >= 3.4 """ return node.value def node_assign(self, node, val): """Assign a value (not the node.value object) to a node. This is used by on_assign, but also by for, list comprehension, etc. """ if node.__class__ == ast.Name: if not valid_symbol_name(node.id) or node.id in self.readonly_symbols: errmsg = "invalid symbol name (reserved word?) %s" % node.id self.raise_exception(node, exc=NameError, msg=errmsg) self.symtable[node.id] = val if node.id in self.no_deepcopy: self.no_deepcopy.remove(node.id) elif node.__class__ == ast.Attribute: if node.ctx.__class__ == ast.Load: msg = "cannot assign to attribute %s" % node.attr self.raise_exception(node, exc=AttributeError, msg=msg) setattr(self.run(node.value), node.attr, val) elif node.__class__ == ast.Subscript: sym = self.run(node.value) xslice = self.run(node.slice) if isinstance(node.slice, ast.Index): sym[xslice] = val elif isinstance(node.slice, ast.Slice): sym[slice(xslice.start, xslice.stop)] = val elif isinstance(node.slice, ast.ExtSlice): sym[xslice] = val elif node.__class__ in (ast.Tuple, ast.List): if len(val) == len(node.elts): for telem, tval in zip(node.elts, val): self.node_assign(telem, tval) else: raise ValueError('too many values to unpack') def on_attribute(self, node): # ('value', 'attr', 'ctx') """Extract attribute.""" ctx = node.ctx.__class__ if ctx == ast.Store: msg = "attribute for storage: shouldn't be here!" self.raise_exception(node, exc=RuntimeError, msg=msg) sym = self.run(node.value) if ctx == ast.Del: return delattr(sym, node.attr) # ctx is ast.Load fmt = "cannnot access attribute '%s' for %s" if node.attr not in UNSAFE_ATTRS: fmt = "no attribute '%s' for %s" try: return getattr(sym, node.attr) except AttributeError: pass # AttributeError or accessed unsafe attribute obj = self.run(node.value) msg = fmt % (node.attr, obj) self.raise_exception(node, exc=AttributeError, msg=msg) def on_assign(self, node): # ('targets', 'value') """Simple assignment.""" val = self.run(node.value) for tnode in node.targets: self.node_assign(tnode, val) return def on_augassign(self, node): # ('target', 'op', 'value') """Augmented assign.""" return self.on_assign(ast.Assign(targets=[node.target], value=ast.BinOp(left=node.target, op=node.op, right=node.value))) def on_slice(self, node): # ():('lower', 'upper', 'step') """Simple slice.""" return slice(self.run(node.lower), self.run(node.upper), self.run(node.step)) def on_extslice(self, node): # ():('dims',) """Extended slice.""" return tuple([self.run(tnode) for tnode in node.dims]) def on_subscript(self, node): # ('value', 'slice', 'ctx') """Subscript handling -- one of the tricky parts.""" val = self.run(node.value) nslice = self.run(node.slice) ctx = node.ctx.__class__ if ctx in (ast.Load, ast.Store): if isinstance(node.slice, (ast.Index, ast.Slice, ast.Ellipsis)): return val.__getitem__(nslice) elif isinstance(node.slice, ast.ExtSlice): return val[nslice] else: msg = "subscript with unknown context" self.raise_exception(node, msg=msg) def on_delete(self, node): # ('targets',) """Delete statement.""" for tnode in node.targets: if tnode.ctx.__class__ != ast.Del: break children = [] while tnode.__class__ == ast.Attribute: children.append(tnode.attr) tnode = tnode.value if tnode.__class__ == ast.Name and tnode.id not in self.readonly_symbols: children.append(tnode.id) children.reverse() self.symtable.pop('.'.join(children)) else: msg = "could not delete symbol" self.raise_exception(node, msg=msg) def on_unaryop(self, node): # ('op', 'operand') """Unary operator.""" return op2func(node.op)(self.run(node.operand)) def on_binop(self, node): # ('left', 'op', 'right') """Binary operator.""" return op2func(node.op)(self.run(node.left), self.run(node.right)) def on_boolop(self, node): # ('op', 'values') """Boolean operator.""" val = self.run(node.values[0]) is_and = ast.And == node.op.__class__ if (is_and and val) or (not is_and and not val): for n in node.values[1:]: val = op2func(node.op)(val, self.run(n)) if (is_and and not val) or (not is_and and val): break return val def on_compare(self, node): # ('left', 'ops', 'comparators') """comparison operators, including chained comparisons (a 0: e_type, e_value, e_tback = self.error[-1].exc_info for hnd in node.handlers: htype = None if hnd.type is not None: htype = builtins.get(hnd.type.id, None) if htype is None or isinstance(e_type(), htype): self.error = [] if hnd.name is not None: self.node_assign(hnd.name, e_value) for tline in hnd.body: self.run(tline) break break if no_errors and hasattr(node, 'orelse'): for tnode in node.orelse: self.run(tnode) if hasattr(node, 'finalbody'): for tnode in node.finalbody: self.run(tnode) def on_raise(self, node): # ('type', 'inst', 'tback') """Raise statement: note difference for python 2 and 3.""" if PY3: excnode = node.exc msgnode = node.cause else: excnode = node.type msgnode = node.inst out = self.run(excnode) msg = ' '.join(out.args) msg2 = self.run(msgnode) if msg2 not in (None, 'None'): msg = "%s: %s" % (msg, msg2) self.raise_exception(None, exc=out.__class__, msg=msg, expr='') def on_call(self, node): """Function execution.""" # ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too) func = self.run(node.func) if not hasattr(func, '__call__') and not isinstance(func, type): msg = "'%s' is not callable!!" % (func) self.raise_exception(node, exc=TypeError, msg=msg) args = [self.run(targ) for targ in node.args] starargs = getattr(node, 'starargs', None) if starargs is not None: args = args + self.run(starargs) keywords = {} if PY3 and func == print: keywords['file'] = self.writer for key in node.keywords: if not isinstance(key, ast.keyword): msg = "keyword error in function call '%s'" % (func) self.raise_exception(node, msg=msg) keywords[key.arg] = self.run(key.value) kwargs = getattr(node, 'kwargs', None) if kwargs is not None: keywords.update(self.run(kwargs)) try: return func(*args, **keywords) except Exception as ex: self.raise_exception( node, msg="Error running function call '%s' with args %s and " "kwargs %s: %s" % (func.__name__, args, keywords, ex)) def on_arg(self, node): # ('test', 'msg') """Arg for function definitions.""" return node.arg def on_functiondef(self, node): """Define procedures.""" # ('name', 'args', 'body', 'decorator_list') if node.decorator_list: raise Warning("decorated procedures not supported!") kwargs = [] if not valid_symbol_name(node.name) or node.name in self.readonly_symbols: errmsg = "invalid function name (reserved word?) %s" % node.name self.raise_exception(node, exc=NameError, msg=errmsg) offset = len(node.args.args) - len(node.args.defaults) for idef, defnode in enumerate(node.args.defaults): defval = self.run(defnode) keyval = self.run(node.args.args[idef+offset]) kwargs.append((keyval, defval)) if PY3: args = [tnode.arg for tnode in node.args.args[:offset]] else: args = [tnode.id for tnode in node.args.args[:offset]] doc = None nb0 = node.body[0] if isinstance(nb0, ast.Expr) and isinstance(nb0.value, ast.Str): doc = nb0.value.s varkws = node.args.kwarg vararg = node.args.vararg if PY3 and isinstance(vararg, ast.arg): vararg = vararg.arg if PY3 and isinstance(varkws, ast.arg): varkws = varkws.arg self.symtable[node.name] = Procedure(node.name, self, doc=doc, lineno=self.lineno, body=node.body, args=args, kwargs=kwargs, vararg=vararg, varkws=varkws) if node.name in self.no_deepcopy: self.no_deepcopy.remove(node.name) class Procedure(object): """Procedure: user-defined function for asteval. This stores the parsed ast nodes as from the 'functiondef' ast node for later evaluation. """ def __init__(self, name, interp, doc=None, lineno=0, body=None, args=None, kwargs=None, vararg=None, varkws=None): """TODO: docstring in public method.""" self.__ininit__ = True self.name = name self.__name__ = self.name self.__asteval__ = interp self.raise_exc = self.__asteval__.raise_exception self.__doc__ = doc self.body = body self.argnames = args self.kwargs = kwargs self.vararg = vararg self.varkws = varkws self.lineno = lineno self.__ininit__ = False def __setattr__(self, attr, val): if not getattr(self, '__ininit__', True): self.raise_exc(None, exc=TypeError, msg="procedure is read-only") self.__dict__[attr] = val def __dir__(self): return ['name'] def __repr__(self): """TODO: docstring in magic method.""" sig = "" if len(self.argnames) > 0: sig = "%s%s" % (sig, ', '.join(self.argnames)) if self.vararg is not None: sig = "%s, *%s" % (sig, self.vararg) if len(self.kwargs) > 0: if len(sig) > 0: sig = "%s, " % sig _kw = ["%s=%s" % (k, v) for k, v in self.kwargs] sig = "%s%s" % (sig, ', '.join(_kw)) if self.varkws is not None: sig = "%s, **%s" % (sig, self.varkws) sig = "" % (self.name, sig) if self.__doc__ is not None: sig = "%s\n %s" % (sig, self.__doc__) return sig def __call__(self, *args, **kwargs): """TODO: docstring in public method.""" symlocals = {} args = list(args) nargs = len(args) nkws = len(kwargs) nargs_expected = len(self.argnames) # check for too few arguments, but the correct keyword given if (nargs < nargs_expected) and nkws > 0: for name in self.argnames[nargs:]: if name in kwargs: args.append(kwargs.pop(name)) nargs = len(args) nargs_expected = len(self.argnames) nkws = len(kwargs) if nargs < nargs_expected: msg = "%s() takes at least %i arguments, got %i" self.raise_exc(None, exc=TypeError, msg=msg % (self.name, nargs_expected, nargs)) # check for multiple values for named argument if len(self.argnames) > 0 and kwargs is not None: msg = "multiple values for keyword argument '%s' in Procedure %s" for targ in self.argnames: if targ in kwargs: self.raise_exc(None, exc=TypeError, msg=msg % (targ, self.name), lineno=self.lineno) # check more args given than expected, varargs not given if nargs != nargs_expected: msg = None if nargs < nargs_expected: msg = 'not enough arguments for Procedure %s()' % self.name msg = '%s (expected %i, got %i)' % (msg, nargs_expected, nargs) self.raise_exc(None, exc=TypeError, msg=msg) if nargs > nargs_expected and self.vararg is None: if nargs - nargs_expected > len(self.kwargs): msg = 'too many arguments for %s() expected at most %i, got %i' msg = msg % (self.name, len(self.kwargs)+nargs_expected, nargs) self.raise_exc(None, exc=TypeError, msg=msg) for i, xarg in enumerate(args[nargs_expected:]): kw_name = self.kwargs[i][0] if kw_name not in kwargs: kwargs[kw_name] = xarg for argname in self.argnames: symlocals[argname] = args.pop(0) try: if self.vararg is not None: symlocals[self.vararg] = tuple(args) for key, val in self.kwargs: if key in kwargs: val = kwargs.pop(key) symlocals[key] = val if self.varkws is not None: symlocals[self.varkws] = kwargs elif len(kwargs) > 0: msg = 'extra keyword arguments for Procedure %s (%s)' msg = msg % (self.name, ','.join(list(kwargs.keys()))) self.raise_exc(None, msg=msg, exc=TypeError, lineno=self.lineno) except (ValueError, LookupError, TypeError, NameError, AttributeError): msg = 'incorrect arguments for Procedure %s' % self.name self.raise_exc(None, msg=msg, lineno=self.lineno) save_symtable = self.__asteval__.symtable.copy() self.__asteval__.symtable.update(symlocals) self.__asteval__.retval = None retval = None # evaluate script of function for node in self.body: self.__asteval__.run(node, expr='<>', lineno=self.lineno) if len(self.__asteval__.error) > 0: break if self.__asteval__.retval is not None: retval = self.__asteval__.retval self.__asteval__.retval = None if retval is ReturnedNone: retval = None break self.__asteval__.symtable = save_symtable symlocals = None return retval python-asteval-0.9.17/asteval/astutils.py000066400000000000000000000403331356473326000204630ustar00rootroot00000000000000""" utility functions for asteval Matthew Newville , The University of Chicago """ from __future__ import division, print_function import io import re import ast import math import numbers from sys import exc_info, version_info from tokenize import NAME as tk_NAME def check_pyversion(): version_major, version_minor = version_info[0], version_info[1] if version_major == 3 and version_minor < 5: raise SystemError("Python 3.0 to 3.4 are not supported") if version_major == 2 and version_minor < 7: raise SystemError("Python 2.6 or earlier are not supported") return version_major == 3 if version_info > (3, 4): from tokenize import tokenize as generate_tokens, ENCODING as tk_ENCODING else: from tokenize import generate_tokens tk_ENCODING = None HAS_NUMPY = False numpy = None try: import numpy ndarr = numpy.ndarray HAS_NUMPY = True except ImportError: pass MAX_EXPONENT = 10000 MAX_STR_LEN = 2 << 17 # 256KiB MAX_SHIFT = 1000 MAX_OPEN_BUFFER = 2 << 17 RESERVED_WORDS = ('and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'True', 'False', 'None', 'eval', 'execfile', '__import__', '__package__') NAME_MATCH = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$").match UNSAFE_ATTRS = ('__subclasses__', '__bases__', '__globals__', '__code__', '__closure__', '__func__', '__self__', '__module__', '__dict__', '__class__', '__call__', '__get__', '__getattribute__', '__subclasshook__', '__new__', '__init__', 'func_globals', 'func_code', 'func_closure', 'im_class', 'im_func', 'im_self', 'gi_code', 'gi_frame', '__asteval__', 'f_locals', '__mro__') # inherit these from python's __builtins__ FROM_PY = ('ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplementedError', 'OSError', 'OverflowError', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'ValueError', 'Warning', 'ZeroDivisionError', 'abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'bytes', 'chr', 'complex', 'dict', 'dir', 'divmod', 'enumerate', 'filter', 'float', 'format', 'frozenset', 'hash', 'hex', 'id', 'int', 'isinstance', 'len', 'list', 'map', 'max', 'min', 'oct', 'ord', 'pow', 'range', 'repr', 'reversed', 'round', 'set', 'slice', 'sorted', 'str', 'sum', 'tuple', 'zip') # inherit these from python's math FROM_MATH = ('acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc') FROM_NUMPY = ('Inf', 'NAN', 'abs', 'add', 'alen', 'all', 'amax', 'amin', 'angle', 'any', 'append', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argsort', 'argwhere', 'around', 'array', 'array2string', 'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray', 'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'bool', 'broadcast', 'broadcast_arrays', 'byte', 'c_', 'cdouble', 'ceil', 'cfloat', 'chararray', 'choose', 'clip', 'clongdouble', 'clongfloat', 'column_stack', 'common_type', 'complex', 'complex128', 'complex64', 'complex_', 'complexfloating', 'compress', 'concatenate', 'conjugate', 'convolve', 'copy', 'copysign', 'corrcoef', 'correlate', 'cos', 'cosh', 'cov', 'cross', 'csingle', 'cumprod', 'cumsum', 'datetime_data', 'deg2rad', 'degrees', 'delete', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'divide', 'dot', 'double', 'dsplit', 'dstack', 'dtype', 'e', 'ediff1d', 'empty', 'empty_like', 'equal', 'exp', 'exp2', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fill_diagonal', 'finfo', 'fix', 'flatiter', 'flatnonzero', 'fliplr', 'flipud', 'float', 'float32', 'float64', 'float_', 'floating', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_parser', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'fv', 'genfromtxt', 'getbufsize', 'geterr', 'gradient', 'greater', 'greater_equal', 'hamming', 'hanning', 'histogram', 'histogram2d', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'iinfo', 'imag', 'in1d', 'index_exp', 'indices', 'inexact', 'inf', 'info', 'infty', 'inner', 'insert', 'int', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'int_asbuffer', 'intc', 'integer', 'interp', 'intersect1d', 'intp', 'invert', 'ipmt', 'irr', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isinf', 'isnan', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'iterable', 'ix_', 'kaiser', 'kron', 'ldexp', 'left_shift', 'less', 'less_equal', 'linspace', 'little_endian', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'long', 'longcomplex', 'longdouble', 'longfloat', 'longlong', 'mafromtxt', 'mask_indices', 'mat', 'matrix', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'minimum', 'mintypecode', 'mirr', 'mod', 'modf', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nanmax', 'nanmin', 'nansum', 'ndarray', 'ndenumerate', 'ndfromtxt', 'ndim', 'ndindex', 'negative', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'nper', 'npv', 'number', 'obj2sctype', 'ogrid', 'ones', 'ones_like', 'outer', 'packbits', 'percentile', 'pi', 'piecewise', 'place', 'pmt', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polysub', 'polyval', 'power', 'ppmt', 'prod', 'product', 'ptp', 'put', 'putmask', 'pv', 'r_', 'rad2deg', 'radians', 'rank', 'rate', 'ravel', 'real', 'real_if_close', 'reciprocal', 'record', 'remainder', 'repeat', 'reshape', 'resize', 'restoredot', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_', 'sctype2char', 'searchsorted', 'select', 'setbufsize', 'setdiff1d', 'seterr', 'setxor1d', 'shape', 'short', 'sign', 'signbit', 'signedinteger', 'sin', 'sinc', 'single', 'singlecomplex', 'sinh', 'size', 'sometrue', 'sort', 'sort_complex', 'spacing', 'split', 'sqrt', 'square', 'squeeze', 'std', 'str', 'str_', 'subtract', 'sum', 'swapaxes', 'take', 'tan', 'tanh', 'tensordot', 'tile', 'trace', 'transpose', 'trapz', 'tri', 'tril', 'tril_indices', 'tril_indices_from', 'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc', 'ubyte', 'uint', 'uint0', 'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong', 'union1d', 'unique', 'unravel_index', 'unsignedinteger', 'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'vsplit', 'vstack', 'where', 'who', 'zeros', 'zeros_like', 'fft', 'linalg', 'polynomial', 'random') NUMPY_RENAMES = {'ln': 'log', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'atan2': 'arctan2', 'atanh': 'arctanh', 'acosh': 'arccosh', 'asinh': 'arcsinh'} def _open(filename, mode='r', buffering=0): """read only version of open()""" if mode not in ('r', 'rb', 'rU'): raise RuntimeError("Invalid open file mode, must be 'r', 'rb', or 'rU'") if buffering > MAX_OPEN_BUFFER: raise RuntimeError("Invalid buffering value, max buffer size is {}".format(MAX_OPEN_BUFFER)) return open(filename, mode, buffering) def _type(obj, *varargs, **varkws): """type that prevents varargs and varkws""" return type(obj).__name__ LOCALFUNCS = {'open': _open, 'type': _type} # Safe versions of functions to prevent denial of service issues def safe_pow(base, exp): """safe version of pow""" if isinstance(exp, numbers.Number): if exp > MAX_EXPONENT: raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT)) elif HAS_NUMPY: if isinstance(exp, numpy.ndarray): if numpy.nanmax(exp) > MAX_EXPONENT: raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT)) return base ** exp def safe_mult(a, b): """safe version of multiply""" if isinstance(a, str) and isinstance(b, int) and len(a) * b > MAX_STR_LEN: raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN)) return a * b def safe_add(a, b): """safe version of add""" if isinstance(a, str) and isinstance(b, str) and len(a) + len(b) > MAX_STR_LEN: raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN)) return a + b def safe_lshift(a, b): """safe version of lshift""" if isinstance(b, numbers.Number): if b > MAX_SHIFT: raise RuntimeError("Invalid left shift, max left shift is {}".format(MAX_SHIFT)) elif HAS_NUMPY: if isinstance(b, numpy.ndarray): if numpy.nanmax(b) > MAX_SHIFT: raise RuntimeError("Invalid left shift, max left shift is {}".format(MAX_SHIFT)) return a << b OPERATORS = {ast.Is: lambda a, b: a is b, ast.IsNot: lambda a, b: a is not b, ast.In: lambda a, b: a in b, ast.NotIn: lambda a, b: a not in b, ast.Add: safe_add, ast.BitAnd: lambda a, b: a & b, ast.BitOr: lambda a, b: a | b, ast.BitXor: lambda a, b: a ^ b, ast.Div: lambda a, b: a / b, ast.FloorDiv: lambda a, b: a // b, ast.LShift: safe_lshift, ast.RShift: lambda a, b: a >> b, ast.Mult: safe_mult, ast.Pow: safe_pow, ast.Sub: lambda a, b: a - b, ast.Mod: lambda a, b: a % b, ast.And: lambda a, b: a and b, ast.Or: lambda a, b: a or b, ast.Eq: lambda a, b: a == b, ast.Gt: lambda a, b: a > b, ast.GtE: lambda a, b: a >= b, ast.Lt: lambda a, b: a < b, ast.LtE: lambda a, b: a <= b, ast.NotEq: lambda a, b: a != b, ast.Invert: lambda a: ~a, ast.Not: lambda a: not a, ast.UAdd: lambda a: +a, ast.USub: lambda a: -a} def valid_symbol_name(name): """Determine whether the input symbol name is a valid name. Arguments --------- name : str name to check for validity. Returns -------- valid : bool whether name is a a valid symbol name This checks for Python reserved words and that the name matches the regular expression ``[a-zA-Z_][a-zA-Z0-9_]`` """ if name in RESERVED_WORDS: return False gen = generate_tokens(io.BytesIO(name.encode('utf-8')).readline) typ, _, start, end, _ = next(gen) if typ == tk_ENCODING: typ, _, start, end, _ = next(gen) return typ == tk_NAME and start == (1, 0) and end == (1, len(name)) def op2func(op): """Return function for operator nodes.""" return OPERATORS[op.__class__] class Empty: """Empty class.""" def __init__(self): """TODO: docstring in public method.""" pass def __nonzero__(self): """TODO: docstring in magic method.""" return False ReturnedNone = Empty() class ExceptionHolder(object): """Basic exception handler.""" def __init__(self, node, exc=None, msg='', expr=None, lineno=None): """TODO: docstring in public method.""" self.node = node self.expr = expr self.msg = msg self.exc = exc self.lineno = lineno self.exc_info = exc_info() if self.exc is None and self.exc_info[0] is not None: self.exc = self.exc_info[0] if self.msg == '' and self.exc_info[1] is not None: self.msg = self.exc_info[1] def get_error(self): """Retrieve error data.""" col_offset = -1 if self.node is not None: try: col_offset = self.node.col_offset except AttributeError: pass try: exc_name = self.exc.__name__ except AttributeError: exc_name = str(self.exc) if exc_name in (None, 'None'): exc_name = 'UnknownError' out = [" %s" % self.expr] if col_offset > 0: out.append(" %s^^^" % ((col_offset)*' ')) out.append(str(self.msg)) return (exc_name, '\n'.join(out)) class NameFinder(ast.NodeVisitor): """Find all symbol names used by a parsed node.""" def __init__(self): """TODO: docstring in public method.""" self.names = [] ast.NodeVisitor.__init__(self) def generic_visit(self, node): """TODO: docstring in public method.""" if node.__class__.__name__ == 'Name': if node.ctx.__class__ == ast.Load and node.id not in self.names: self.names.append(node.id) ast.NodeVisitor.generic_visit(self, node) builtins = __builtins__ if not isinstance(builtins, dict): builtins = builtins.__dict__ def get_ast_names(astnode): """Return symbol Names from an AST node.""" finder = NameFinder() finder.generic_visit(astnode) return finder.names def make_symbol_table(use_numpy=True, **kws): """Create a default symboltable, taking dict of user-defined symbols. Arguments --------- numpy : bool, optional whether to include symbols from numpy kws : optional additional symbol name, value pairs to include in symbol table Returns -------- symbol_table : dict a symbol table that can be used in `asteval.Interpereter` """ symtable = {} for sym in FROM_PY: if sym in builtins: symtable[sym] = builtins[sym] for sym in FROM_MATH: if hasattr(math, sym): symtable[sym] = getattr(math, sym) if HAS_NUMPY and use_numpy: for sym in FROM_NUMPY: if hasattr(numpy, sym): symtable[sym] = getattr(numpy, sym) for name, sym in NUMPY_RENAMES.items(): if hasattr(numpy, sym): symtable[name] = getattr(numpy, sym) symtable.update(LOCALFUNCS) symtable.update(kws) return symtable python-asteval-0.9.17/doc/000077500000000000000000000000001356473326000153445ustar00rootroot00000000000000python-asteval-0.9.17/doc/Makefile000066400000000000000000000063051356473326000170100ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build INSTALLDIR = /home/newville/public_html/asteval/ # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest latexpdf .PHONY: all install html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." asteval.pdf: latex cd $(BUILDDIR)/latex && make all-pdf cp -pr $(BUILDDIR)/latex/asteval.pdf ./asteval.pdf all: html install: all cp -pr $(BUILDDIR)/latex/asteval.pdf $(INSTALLDIR)/asteval.pdf cp -pr $(BUILDDIR)/html/* $(INSTALLDIR)/. help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex @echo @echo "Build finished; the LaTeX files are in _build/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex @echo "Running LaTeX files through pdflatex..." make -C _build/latex all-pdf @echo "pdflatex finished; the PDF files are in _build/latex." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." python-asteval-0.9.17/doc/_static/000077500000000000000000000000001356473326000167725ustar00rootroot00000000000000python-asteval-0.9.17/doc/_static/empty000066400000000000000000000000001356473326000200410ustar00rootroot00000000000000python-asteval-0.9.17/doc/_templates/000077500000000000000000000000001356473326000175015ustar00rootroot00000000000000python-asteval-0.9.17/doc/_templates/indexsidebar.html000066400000000000000000000004551356473326000230340ustar00rootroot00000000000000

Downloads

Current version: {{ release }}

Downloads: PyPI (Python.org)

try pip install asteval

Development version:
    github.com


python-asteval-0.9.17/doc/api.rst000066400000000000000000000113031356473326000166450ustar00rootroot00000000000000.. _asteval_api: ======================== asteval reference ======================== .. _numpy: http://docs.scipy.org/doc/numpy .. module:: asteval The asteval module has a pretty simple interface, providing an :class:`Interpreter` class which creates an Interpreter of expressions and code. There are a few options available to control what language features to support, how to deal with writing to standard output and standard error, and specifying the symbol table. There are also a few convenience functions: :func:`valid_symbol_name` is useful for tesing the validity of symbol names, and :func:`make_symbol_table` is useful for creating symbol tables that may be pre-loaded with custom symbols and functions. The :class:`Interpreter` class ========================================= .. autoclass:: Interpreter By default, the symbol table will be created with :func:`make_symbol_table` that will include several standard python builtin functions, several functions from the :py:mod:`math` module and (if available and not turned off) several functions from `numpy`_. The ``writer`` argument can be used to provide a place to send all output that would normally go to :py:data:`sys.stdout`. The default is, of course, to send output to :py:data:`sys.stdout`. Similarly, ``err_writer`` will be used for output that will otherwise be sent to :py:data:`sys.stderr`. The ``use_numpy`` argument can be used to control whether functions from `numpy`_ are loaded into the symbol table. By default, the interpreter will support many Python language constructs, including * advanced slicing: ``a[::-1], array[-3:, :, ::2]`` * if-elif-else conditionals * for loops, with ``else`` * while loops, with ``else`` * try-except-finally blocks * function definitions * augmented assignments: ``x += 1`` * if-expressions: ``x = a if TEST else b`` * list comprehension: ``out = [sqrt(i) for i in values]`` with the exception of slicing, each of these features can be turned off with the appropriate ``no_XXX`` option. To turn off all these optional constructs, and create a simple expression calculator, use ``minimal=True``. Many Python syntax elements are not supported at all, including: Import, Exec, Lambda, Class, Global, Generators, Yield, Decorators In addition, many actions that are known to be unsafe (such as inspecting objects to get at their base classes) are also not allowed. An Interpreter instance has many methods, but most of them are implementation details for how to handle particular AST nodes, and should not be considered as part of the usable API. The methods described be low, and the examples elsewhere in this documentation should be used as the stable API. .. method:: eval(expression[, lineno=0[, show_errors=True]]) evaluate the expression, returning the result. :param expression: code to evaluate. :type expression: string :param lineno: line number (for error messages). :type lineno: int :param show_errors: whether to print error messages or leave them in the :attr:`errors` list. :type show_errors: bool .. method:: __call__(expression[, lineno=0[, show_errors=True]]) same as :meth:`eval`. That is:: >>> from asteval import Interpreter >>> a = Interpreter() >>> a('x = 1') instead of:: >>> a.eval('x = 1') .. attribute:: symtable the symbol table. A dictionary with symbol names as keys, and object values (data and functions). For full control of the symbol table, you can simply access the :attr:`symtable` object, inserting, replacing, or removing symbols to alter what symbols are known to your interpreter. You can also access the :attr:`symtable` to retrieve results. .. attribute:: error a list of error information, filled on exceptions. You can test this after each call of the interpreter. It will be empty if the last execution was successful. If an error occurs, this will contain a liste of Exceptions raised. .. attribute:: error_msg the most recent error message. Utility Functions ==================== .. autofunction:: valid_symbol_name .. autofunction:: make_symbol_table To make and use a custom symbol table, one might do this:: from asteval import Interpreter, make_symbol_table import numpy as np def cosd(x): "cos with angle in degrees" return np.cos(np.radians(x)) def sind(x): "sin with angle in degrees" return np.sin(np.radians(x)) def tand(x): "tan with angle in degrees" return np.tan(np.radians(x)) syms = make_symbol_table(use_numpy=True, cosd=cosd, sind=sind, tand=tand) aeval = Interpreter(symtable=syms) print(aeval("sind(30)"))) which will print ``0.5``. python-asteval-0.9.17/doc/basics.rst000066400000000000000000000136001356473326000173420ustar00rootroot00000000000000================ Using asteval ================ This chapter gives a quick overview of asteval, showing basic usage and the most important features. Further details can be found in the next chapter (:ref:`asteval_api`). creating and using an asteval Interpreter ============================================= The asteval module is very easy to use. Import the module and create an Interpreter: >>> from asteval import Interpreter >>> aeval = Interpreter() and now you have an embedded interpreter for a procedural, mathematical language that is very much like python:: >>> aeval('x = sqrt(3)') >>> aeval('print x') 1.73205080757 >>> aeval('''for i in range(10): print i, sqrt(i), log(1+1) ''') 0 0.0 0.0 1 1.0 0.69314718056 2 1.41421356237 1.09861228867 3 1.73205080757 1.38629436112 4 2.0 1.60943791243 5 2.2360679775 1.79175946923 6 2.44948974278 1.94591014906 7 2.64575131106 2.07944154168 8 2.82842712475 2.19722457734 9 3.0 2.30258509299 accessing the symbol table ============================= The symbol table (that is, the mapping between variable and function names and the underlying objects) is a simple dictionary held in the :attr:`symtable` attribute of the interpreter, and can be read or written to:: >>> aeval('x = sqrt(3)') >>> aeval.symtable['x'] 1.73205080757 >>> aeval.symtable['y'] = 100 >>> aeval('print y/8') 12.5 Note here the use of true division even though the operands are integers. As with Python itself, valid symbol names must match the basic regular expression pattern:: valid_name = [a-zA-Z_][a-zA-Z0-9_]* In addition, certain names are reserved in Python, and cannot be used within the asteval interpreter. These reserved words are: and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, True, False, None, eval, execfile, __import__, __package__ built-in functions ======================= At startup, many symbols are loaded into the symbol table from Python's builtins and the **math** module. The builtins include several basic Python functions: abs, all, any, bin, bool, bytearray, bytes, chr, complex, dict, dir, divmod, enumerate, filter, float, format, frozenset, hash, hex, id, int, isinstance, len, list, map, max, min, oct, ord, pow, range, repr, reversed, round, set, slice, sorted, str, sum, tuple, type, zip and a large number of named exceptions: ArithmeticError, AssertionError, AttributeError, BaseException, BufferError, BytesWarning, DeprecationWarning, EOFError, EnvironmentError, Exception, False, FloatingPointError, GeneratorExit, IOError, ImportError, ImportWarning, IndentationError, IndexError, KeyError, KeyboardInterrupt, LookupError, MemoryError, NameError, None, NotImplemented, NotImplementedError, OSError, OverflowError, ReferenceError, RuntimeError, RuntimeWarning, StopIteration, SyntaxError, SyntaxWarning, SystemError, SystemExit, True, TypeError, UnboundLocalError, UnicodeDecodeError, UnicodeEncodeError, UnicodeError, UnicodeTranslateError, UnicodeWarning, ValueError, Warning, ZeroDivisionError The symbols imported from Python's *math* module include: acos, acosh, asin, asinh, atan, atan2, atanh, ceil, copysign, cos, cosh, degrees, e, exp, fabs, factorial, floor, fmod, frexp, fsum, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, pi, pow, radians, sin, sinh, sqrt, tan, tanh, trunc .. _numpy: http://docs.scipy.org/doc/numpy If available, a very large number (~400) additional symbols are imported from `numpy`_. conditionals and loops ========================== If-then-else blocks, for-loops (including the optional *else* block) and while loops (also including optional *else* block) are supported, and work exactly as they do in python. Thus: >>> code = """ sum = 0 for i in range(10): sum += i*sqrt(*1.0) if i % 4 == 0: sum = sum + 1 print("sum = ", sum) """ >>> aeval(code) sum = 114.049534067 printing =============== For printing, asteval emulates Python's native :func:`print` function (for Python 3) and :data:`print` statement (for Python 2). That is, the behavior mimics the version of Python used. You can change where output is sent with the ``writer`` argument when creating the interpreter. By default, outputs are sent to :py:data:`sys.stdout`. writing functions =================== User-defined functions can be written and executed, as in python with a *def* block, for example:: >>> from asteval import Interpreter >>> aeval = Interpreter() >>> code = """def func(a, b, norm=1.0): ... return (a + b)/norm ... """ >>> aeval(code) >>> aeval("func(1, 3, norm=10.0)") 0.4 exceptions =============== Asteval monitors and caches exceptions in the evaluated code. Brief error messages are printed (with Python's print statement or function, and so using standard output by default), and the full set of exceptions is kept in the :attr:`error` attribute of the :class:`Interpreter` instance. This :attr:`error` attribute is a list of instances of the asteval :class:`ExceptionHolder` class, which is accessed through the :meth:`get_error` method. The :attr:`error` attribute is reset to an empty list at the beginning of each :meth:`eval`, so that errors are from only the most recent :meth:`eval`. Thus, to handle and re-raise exceptions from your Python code in a simple REPL loop, you'd want to do something similar to >>> from asteval import Interpreter >>> aeval = Interpreter() >>> while True: >>> inp_string = raw_input('dsl:>') >>> result = aeval(inp_string) >>> if len(aeval.error)>0: >>> for err in aeval.error: >>> print(err.get_error()) >>> else: >>> print(result) python-asteval-0.9.17/doc/conf.py000066400000000000000000000150621356473326000166470ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # asteval documentation build configuration file # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.append(os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.intersphinx'] intersphinx_mapping = {'py': ('http://docs.python.org/', None)} # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'asteval' copyright = u'2014, Matthew Newville, The University of Chicago' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. import asteval release = asteval.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'sphinxdoc' # html_theme = 'nature' # html_theme = 'agogo' # html_theme_options = {'pagewidth':'85em', 'documentwidth':'60em', 'sidebarwidth': '25em', # # 'headercolor1': '#000080', # # 'headercolor2': '#0000A0', # } # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None html_title = 'ASTEVAL: Minimal Python AST evaluator' # A shorter title for the navigation bar. Default is the same as html_title. html_short_title = 'ASTEVAL: Minimal Python AST evaluator' # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = False # True # Custom sidebar templates, maps document names to template names. html_sidebars = {'index': ['indexsidebar.html','searchbox.html']} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'astevaldoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'asteval.tex', u'asteval documentation', u'Matthew Newville', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True python-asteval-0.9.17/doc/index.rst000066400000000000000000000057111356473326000172110ustar00rootroot00000000000000.. asteval documentation master file, ASTEVAL: Minimal Python AST Evaluator ================================================ .. _numpy: http://docs.scipy.org/doc/numpy The asteval package evaluates mathematical expressions and statements, providing a safer alternative to Python's builtin :py:func:`eval` and a richer, easier to use alternative to :py:func:`ast.literal_eval`. It does this by building an embedded interpreter for a subset of the Python language using Python's :py:mod:`ast` module. The emphasis here and main area of application is the evaluation of mathematical expressions. Because of this, mathematical functions from Python's :py:mod:`math` module are available, and a large number of functions from `numpy`_ will be available if `numpy`_ is installed on your system. While the emphasis is on basic mathematical expressions, many features of the Python language are supported by default. These features include array slicing and subscripting, if-then-else conditionals, while loops, for loops, try-except blocks, list comprehension, and user-defined functions. All objects in the asteval interpreter are truly python objects, and all basic built-in data structures (strings, dictionaries, tuple, lists, numpy arrays) are supported. However, Asteval is by no means an attempt to reproduce Python with its own :py:mod:`ast` module. There are important differences and missing features compared to Python. Many of these absences are intentionally trying to make a safer version of :py:func:`eval`, while some are simply due to the reduced requirements for a small embedded min-language. Some of the main differences and absences include: 1. Variable and function symbol names are held in a simple symbol table - a single dictionary - giving a flat namespace. 2. creating classes is not allowed. 3. importing modules is not allowed. 4. function decorators, generators, yield, and lambda are not supported. 5. Many builtins (:py:func:`eval`, :py:func:`execfile`, :py:func:`getattr`, :py:func:`hasattr`, :py:func:`setattr`, and :py:func:`delattr`) are not allowed. 6. Accessing several private object attributes that can provide access to the python interpreter are not allowed. The effect to make the asteval mini-language look and act very much like miniature version of Python itself focused on mathematical calculations, and with noticeable limitations. Because asteval is suitable for evaluating user-supplied input strings, safety against malicious or incompetent user input is an important concern. Asteval tries as hard as possible to prevent user-supplied input from crashing the Python interpreter or from returning exploitable parts of the Python interpreter. In this sense asteval is certainly safer than using :py:func:`eval`. However, asteval is an open source project written by volunteers, and we cannot guarantee that it is completely safe against malicious attacks. .. toctree:: :maxdepth: 2 installation motivation basics api python-asteval-0.9.17/doc/installation.rst000066400000000000000000000023371356473326000206040ustar00rootroot00000000000000==================================== Downloading and Installation ==================================== .. _numpy: http://docs.scipy.org/doc/numpy .. _github: http://github.com/newville/asteval .. _PyPI: http://pypi.python.org/pypi/asteval/ Requirements ~~~~~~~~~~~~~~~ Asteval is a pure python module with no required dependencies outside of the standard library. Asteval will make use of the `numpy`_ module if available. Version 0.9.17 supports and is tested with Python 2.7, Python 3.5 through 3.8. This is the final version to support Python 2.7. Download and Installation ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The latest stable version of asteval is |release| and is available at `PyPI`_ or as a conda package. You should be able to install asteval with:: pip install asteval or:: conda install -c GSECARS asteval Development Version ~~~~~~~~~~~~~~~~~~~~~~~~ The latest development version can be found at the `github`_ repository, and cloned with:: git clone http://github.com/newville/asteval.git Installation ~~~~~~~~~~~~~~~~~ Installation from source on any platform is:: python setup.py install License ~~~~~~~~~~~~~ The ASTEVAL code is distribution under the following license: .. literalinclude:: ../LICENSE python-asteval-0.9.17/doc/motivation.rst000066400000000000000000000201741356473326000202730ustar00rootroot00000000000000.. _lmfit: http://github.com/lmfit/lmfit-py .. _xraylarch: http://github.com/xraypy/xraylarch ######################## Motivation for asteval ######################## The asteval module allows you to evaluate a large subset of the Python language from within a python program, without using :py:func:`eval`. It is, in effect, a restricted version of Python's built-in :py:func:`eval`, forbidding several actions, and using a simple dictionary as a flat namespace. A completely fair question is: Why is this desirable? That is, why not simply use :py:func:`eval`, or just use Python itself? The short answer is that sometimes you want to allow evaluation of user input, or expose a simple (or even "scientific") calculator inside a larger application. For this, :py:func:`eval` is pretty scary, as it exposes *all* of Python, which makes user input difficult to trust. Since asteval does not support the **import** statement or many other constructs, user code cannot access the :py:mod:`os` and :py:mod:`sys` modules or any functions or classes outside those provided in the symbol table. Many of the other missing features (modules, classes, lambda, yield, generators) are similarly motivated by a desire for a safer version of :py:func:`eval`. The idea for asteval is to make a simple procedural, mathematically oriented language that can be embedded into larger applications. In fact, the asteval module grew out the the need for a simple expression evaluator for scientific applications such as the `lmfit`_ and `xraylarch`_ modules. An early attempt using the pyparsing module worked but was error-prone and difficult to maintain. While the simplest of calculators or expressiona-evaluators is not hard with pyparsing, it turned out that using the Python :py:mod:`ast` module makes for a much easier and feature rich simple calculator scientific calculator, including slicing, complex numbers, keyword arguments to functions, etc. In fact, it is so easy that adding more complex programming constructs like conditionals, loops, exception handling, and even user-defined functions was fairly simple to implement. Importantly, because parsing is done by the :py:mod:`ast` module, whole classes of implementation errors disappear. Valid python expression will be parsed correctly and converted into an Abstract Syntax Tree. Furthermore, the resulting AST is easy to walk through, greatly simplifying evaluation over any other approach. What started as a desire for a simple expression evaluator grew into a quite useable procedural domain-specific language for mathematical applications. Asteval makes no claims about speed. Evaluating the AST involves many function calls, which is going to be slower than Python. In preliminary tests, it's about 4x slower than Python. That said, for certain use cases (see https://stackoverflow.com/questions/34106484), use of asteval and numpy can approach the speed of `eval` and the `numexpr` modules. How Safe is asteval? ======================= Asteval avoids all of the exploits we know about that make :py:func:`eval` dangerous. For reference, see, `Eval is really dangerous `_ and the comments and links therein. From this discussion it is apparent that not only is :py:func:`eval` unsafe, but that it is a difficult prospect to make any program that takes user input perfectly safe. In particular, if a user can cause Python to crash with a segmentation fault, safety cannot be guaranteed. Asteval explicitly forbids the exploits described in the above link, and works hard to prevent malicious code from crashing Python or accessing the underlying operating system. That said, we cannot guarantee that asteval is completely safe from malicious code. We claim only that it is safer than the builtin :py:func:`eval`, and that you might find it useful. Some of the things not allowed in the asteval interpreter for safety reasons include: * importing modules. Neither 'import' nor '__import__' are supported. * create classes or modules. * access to Python's :py:func:`eval`, :py:func:`execfile`, :py:func:`getattr`, :py:func:`hasattr`, :py:func:`setattr`, and :py:func:`delattr`. In addition (and following the discussion in the link above), the following attributes are blacklisted for all objects, and cannot be accessed: __subclasses__, __bases__, __globals__, __code__, __closure__, __func__, __self__, __module__, __dict__, __class__, __call__, __get__, __getattribute__, __subclasshook__, __new__, __init__, func_globals, func_code, func_closure, im_class, im_func, im_self, gi_code, gi_frame f_locals, __mro__ This approach of making a blacklist cannot be guaranteed to be complete, but it does eliminate classes of attacks known to seg-fault the Python. On the other hand, asteval will typically expose numpy ufuncs from the numpy module, and several of these can seg-fault Python without too much trouble. If you're paranoid about safe user input that can never cause a segmentation fault, you'll want to disable the use of numpy. There are important categories of safety that asteval does not even attempt to address. The most important of these is resource hogging, which might be used for a denial-of-service attack. There is no guaranteed timeout on any calculation, and so a reasonable looking calculation such as:: from asteval import Interpreter aeval = Interpreter() txt = """nmax = 1e8 a = sqrt(arange(nmax)) """ aeval.eval(txt) can take a noticeable amount of CPU time. It is not hard to come up with short program that would run for hundreds of years, which probably exceeds anyones threshold for an acceptable run-time. But there simply is not an obvious way to predict how long any code will take to run from the text of the code itself. As a simple example, consider the expression `x**y**z`. For values of `x`, `y`, and `z`. For `x=y=z=5`, runtime will be well under 0.001 seconds. For `x=y=z=8`, runtime will still be under 1 sec. For `x=8, y=9, z=9`, runtime will several seconds. But for `x=y=z=9`, runtime may exceed 1 hour on some machines. In short, runtime cannot be determined lexically. This example also demonstrates there is not a good way to check for a long-running calculation within a single Python process. That calculation is not stuck within the Python interpreter -- it is stuck deep inside C-code. called by the Python interpreter itself, and will not return or allow other threads to run until that calculation is done. That is, from within a single process, there is not a foolproof way to tell `asteval` (or really, even Python) when a calculation has taken too long. The most reliable way to limit run time is to have a second process watching the execution time of the asteval process and interrupt or kill it. For a limited range of problems, you can try to avoid asteval taking too long. For example, you may try to limit the *recursion limit* when executing expressions, with a code like this:: import contextlib @contextlib.contextmanager def limited_recursion(recursion_limit): old_limit = sys.getrecursionlimit() sys.setrecursionlimit(recursion_limit) try: yield finally: sys.setrecursionlimit(old_limit) with limited_recursion(100): Interpreter().eval(...) As an addition security concern, the default list of supported functions does include Python's `open()` which will allow disk access to the untrusted user. If `numpy` is supported, its `load()` and `loadtxt()` functions will also be supported. This doesn't really elevate permissions, but it does allow the user of the `asteval` interpreter to read files with the privileges of the calling program. In some cases, this may not be desireable, and you may want to remove some of these functions from the symbol table, re-implement them, or ensure that your program cannot access information on disk that should be kept private. In summary, while asteval attempts to be safe and is definitely safer than using :py:func:`eval`, there are many ways that asteval could be considered part of an un-safe programming environment. Recommendations for how to improve this situation would be greatly appreciated. python-asteval-0.9.17/requirements.txt000066400000000000000000000001601356473326000200600ustar00rootroot00000000000000## ## pip requirements file. To install dependencies, use ## ## pip install -r requirements.txt ## numpy>=1.6 python-asteval-0.9.17/setup.cfg000066400000000000000000000002401356473326000164140ustar00rootroot00000000000000[versioneer] VCS = git style = pep440 versionfile_source = asteval/_version.py versionfile_build = asteval/_version.py tag_prefix = parentdir_prefix = asteval- python-asteval-0.9.17/setup.py000066400000000000000000000026071356473326000163160ustar00rootroot00000000000000#!/usr/bin/env python from setuptools import setup import versioneer long_description = """ASTEVAL provides a numpy-aware, safe(ish) 'eval' function Emphasis is on mathematical expressions, and so numpy ufuncs are used if available. Symbols are held in the Interpreter symbol table 'symtable': a simple dictionary supporting a simple, flat namespace. Expressions can be compiled into ast node for later evaluation, using the values in the symbol table current at evaluation time. """ install_reqs = [] test_reqs = ['pytest'] setup(name='asteval', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), author='Matthew Newville', author_email='newville@cars.uchicago.edu', url='http://github.com/newville/asteval', license = 'OSI Approved :: MIT License', python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*', description="Safe, minimalistic evaluator of python expression using ast module", long_description=long_description, packages=['asteval'], install_requires=install_reqs, tests_require=test_reqs, classifiers=['Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Operating System :: OS Independent', 'Programming Language :: Python', ], ) python-asteval-0.9.17/tests/000077500000000000000000000000001356473326000157415ustar00rootroot00000000000000python-asteval-0.9.17/tests/test_asteval.py000066400000000000000000001013531356473326000210140ustar00rootroot00000000000000#!/usr/bin/env python """ Base TestCase for asteval """ import ast import os import textwrap import time import unittest import pytest from sys import version_info from tempfile import NamedTemporaryFile from asteval import NameFinder, Interpreter, make_symbol_table, check_pyversion PY3 = check_pyversion() if PY3: from io import StringIO else: from cStringIO import StringIO HAS_NUMPY = False try: import numpy as np from numpy.testing import assert_allclose HAS_NUMPY = True except ImportError: HAS_NUMPY = False class TestCase(unittest.TestCase): """testing of asteval""" def setUp(self): self.interp = Interpreter() self.symtable = self.interp.symtable self.set_stdout() self.set_stderr() def set_stdout(self): self.stdout = NamedTemporaryFile('w', delete=False, prefix='astevaltest') self.interp.writer = self.stdout def read_stdout(self): self.stdout.close() time.sleep(0.1) fname = self.stdout.name with open(self.stdout.name) as inp: out = inp.read() self.set_stdout() os.unlink(fname) return out def set_stderr(self): self.stderr = NamedTemporaryFile('w', delete=False, prefix='astevaltest_stderr') self.interp.err_writer = self.stderr def read_stderr(self): self.stderr.close() time.sleep(0.1) fname = self.stderr.name with open(self.stderr.name) as inp: out = inp.read() self.set_stderr() os.unlink(fname) return out def tearDown(self): if not self.stdout.closed: self.stdout.close() if not self.stderr.closed: self.stderr.close() # noinspection PyBroadException try: os.unlink(self.stdout.name) except: pass try: os.unlink(self.stderr.name) except: pass # noinspection PyUnresolvedReferences def isvalue(self, sym, val): """assert that a symboltable symbol has a particular value""" tval = self.interp.symtable[sym] if HAS_NUMPY and isinstance(val, np.ndarray): assert_allclose(tval, val, rtol=0.01) else: assert(tval == val) def isnear(self, expr, val): tval = self.interp(expr) if HAS_NUMPY: assert_allclose(tval, val, rtol=1.e-4, atol=1.e-4) # noinspection PyUnresolvedReferences def istrue(self, expr): """assert that an expression evaluates to True""" val = self.interp(expr) if HAS_NUMPY and isinstance(val, np.ndarray): val = np.all(val) return self.assertTrue(val) # noinspection PyUnresolvedReferences def isfalse(self, expr): """assert that an expression evaluates to False""" val = self.interp(expr) if HAS_NUMPY and isinstance(val, np.ndarray): val = np.all(val) return self.assertFalse(val) def check_output(self, chk_str, exact=False): self.interp.writer.flush() out = self.read_stdout().split('\n') if out: if exact: return chk_str == out[0] return chk_str in out[0] return False def check_error(self, chk_type='', chk_msg=''): try: errtype, errmsg = self.interp.error[0].get_error() self.assertEqual(errtype, chk_type) if chk_msg: self.assertTrue(chk_msg in errmsg) except IndexError: if chk_type: self.assertTrue(False) class TestEval(TestCase): """testing of asteval""" def test_dict_index(self): """dictionary indexing""" self.interp("a_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}") self.istrue("a_dict['a'] == 1") self.istrue("a_dict['d'] == 4") def test_list_index(self): """list indexing""" self.interp("a_list = ['a', 'b', 'c', 'd', 'o']") self.istrue("a_list[0] == 'a'") self.istrue("a_list[1] == 'b'") self.istrue("a_list[2] == 'c'") def test_tuple_index(self): """tuple indexing""" self.interp("a_tuple = (5, 'a', 'x')") self.istrue("a_tuple[0] == 5") self.istrue("a_tuple[2] == 'x'") def test_string_index(self): """string indexing""" self.interp("a_string = 'hello world'") self.istrue("a_string[0] == 'h'") self.istrue("a_string[6] == 'w'") self.istrue("a_string[-1] == 'd'") self.istrue("a_string[-2] == 'l'") def test_ndarray_index(self): """nd array indexing""" if HAS_NUMPY: self.interp("a_ndarray = 5*arange(20)") assert(self.interp("a_ndarray[2]") == 10) assert(self.interp("a_ndarray[4]") == 20) def test_ndarrayslice(self): """array slicing""" if HAS_NUMPY: self.interp("a_ndarray = arange(200).reshape(10, 20)") self.istrue("a_ndarray[1:3,5:7] == array([[25,26], [45,46]])") self.interp("y = arange(20).reshape(4, 5)") self.istrue("y[:,3] == array([3, 8, 13, 18])") self.istrue("y[...,1] == array([1, 6, 11, 16])") self.interp("y[...,1] = array([2, 2, 2, 2])") self.istrue("y[1,:] == array([5, 2, 7, 8, 9])") def test_while(self): """while loops""" self.interp(textwrap.dedent(""" n=0 while n < 8: n += 1 """)) self.isvalue('n', 8) self.interp(textwrap.dedent(""" n=0 while n < 8: n += 1 if n > 3: break else: n = -1 """)) self.isvalue('n', 4) self.interp(textwrap.dedent(""" n=0 while n < 8: n += 1 else: n = -1 """)) self.isvalue('n', -1) self.interp(textwrap.dedent(""" n, i = 0, 0 while n < 10: n += 1 if n % 2: continue i += 1 print( 'finish: n, i = ', n, i) """)) self.isvalue('n', 10) self.isvalue('i', 5) self.interp(textwrap.dedent(""" n=0 while n < 10: n += 1 print( ' n = ', n) if n > 5: break print( 'finish: n = ', n) """)) self.isvalue('n', 6) def test_while_continue(self): self.interp(textwrap.dedent(""" n, i = 0, 0 while n < 10: n += 1 if n % 2: continue i += 1 print( 'finish: n, i = ', n, i) """)) self.isvalue('n', 10) self.isvalue('i', 5) def test_while_break(self): self.interp(textwrap.dedent(""" n = 0 while n < 10: n += 1 if n > 6: break print( 'finish: n = ', n) """)) self.isvalue('n', 7) # noinspection PyTypeChecker def test_assert(self): """test assert statements""" self.interp.error = [] self.interp('n=6') self.interp('assert n==6') self.check_error(None) self.interp('assert n==7') self.check_error('AssertionError') def test_for(self): """for loops""" self.interp(textwrap.dedent(""" n=0 for i in range(10): n += i """)) self.isvalue('n', 45) self.interp(textwrap.dedent(""" n=0 for i in range(10): n += i else: n = -1 """)) self.isvalue('n', -1) if HAS_NUMPY: self.interp(textwrap.dedent(""" n=0 for i in arange(10): n += i """)) self.isvalue('n', 45) self.interp(textwrap.dedent(""" n=0 for i in arange(10): n += i else: n = -1 """)) self.isvalue('n', -1) def test_for_break(self): self.interp(textwrap.dedent(""" n=0 for i in range(10): n += i if n > 2: break else: n = -1 """)) self.isvalue('n', 3) if HAS_NUMPY: self.interp(textwrap.dedent(""" n=0 for i in arange(10): n += i if n > 2: break else: n = -1 """)) self.isvalue('n', 3) def test_if(self): """runtime errors test""" self.interp(textwrap.dedent(""" zero = 0 if zero == 0: x = 1 if zero != 100: x = x+1 if zero > 2: x = x + 1 else: y = 33 """)) self.isvalue('x', 2) self.isvalue('y', 33) def test_print(self): """print (ints, str, ....)""" self.interp("print(31)") self.check_output('31\n', True) self.interp("print('%s = %.3f' % ('a', 1.2012345))") self.check_output('a = 1.201\n', True) self.interp("print('{0:s} = {1:.2f}'.format('a', 1.2012345))") self.check_output('a = 1.20\n', True) def test_repr(self): """repr of dict, list""" self.interp("x = {'a': 1, 'b': 2, 'c': 3}") self.interp("y = ['a', 'b', 'c']") self.interp("rep_x = repr(x['a'])") self.interp("rep_y = repr(y)") self.interp("rep_y , rep_x") self.interp("repr(None)") self.isvalue("rep_x", "1") self.isvalue("rep_y", "['a', 'b', 'c']") def test_cmp(self): """numeric comparisons""" self.istrue("3 == 3") self.istrue("3.0 == 3") self.istrue("3.0 == 3.0") self.istrue("3 != 4") self.istrue("3.0 != 4") self.istrue("3 >= 1") self.istrue("3 >= 3") self.istrue("3 <= 3") self.istrue("3 <= 5") self.istrue("3 < 5") self.istrue("5 > 3") self.isfalse("3 == 4") self.isfalse("3 > 5") self.isfalse("5 < 3") def test_bool(self): """boolean logic""" self.interp(textwrap.dedent(""" yes = True no = False nottrue = False a = range(7)""")) self.istrue("yes") self.isfalse("no") self.isfalse("nottrue") self.isfalse("yes and no or nottrue") self.isfalse("yes and (no or nottrue)") self.isfalse("(yes and no) or nottrue") self.istrue("yes or no and nottrue") self.istrue("yes or (no and nottrue)") self.isfalse("(yes or no) and nottrue") self.istrue("yes or not no") self.istrue("(yes or no)") self.isfalse("not (yes or yes)") self.isfalse("not (yes or no)") self.isfalse("not (no or yes)") self.istrue("not no or yes") self.isfalse("not yes") self.istrue("not no") def test_bool_coerce(self): """coercion to boolean""" self.istrue("1") self.isfalse("0") self.istrue("'1'") self.isfalse("''") self.istrue("[1]") self.isfalse("[]") self.istrue("(1)") self.istrue("(0,)") self.isfalse("()") self.istrue("dict(y=1)") self.isfalse("{}") # noinspection PyUnresolvedReferences def test_assignment(self): """variables assignment""" self.interp('n = 5') self.isvalue("n", 5) self.interp('s1 = "a string"') self.isvalue("s1", "a string") self.interp('b = (1,2,3)') self.isvalue("b", (1, 2, 3)) if HAS_NUMPY: self.interp('a = 1.*arange(10)') self.isvalue("a", np.arange(10)) self.interp('a[1:5] = 1 + 0.5 * arange(4)') self.isnear("a", np.array([0., 1., 1.5, 2., 2.5, 5., 6., 7., 8., 9.])) def test_names(self): """names test""" self.interp('nx = 1') self.interp('nx1 = 1') if PY3: # use \u escape b/c python 2 complains about file encoding self.interp('\u03bb = 1') self.interp('\u03bb1 = 1') def test_syntaxerrors_1(self): """assignment syntax errors test""" for expr in ('class = 1', 'for = 1', 'if = 1', 'raise = 1', '1x = 1', '1.x = 1', '1_x = 1'): failed = False # noinspection PyBroadException try: self.interp(expr, show_errors=False) except: failed = True self.assertTrue(failed) self.check_error('SyntaxError') def test_unsupportednodes(self): """unsupported nodes""" for expr in ('f = lambda x: x*x', 'yield 10'): failed = False # noinspection PyBroadException try: self.interp(expr, show_errors=False) except: failed = True self.assertTrue(failed) self.check_error('NotImplementedError') def test_syntaxerrors_2(self): """syntax errors test""" for expr in ('x = (1/*)', 'x = 1.A', 'x = A.2'): failed = False # noinspection PyBroadException try: self.interp(expr, show_errors=False) except: # RuntimeError: failed = True self.assertTrue(failed) self.check_error('SyntaxError') def test_runtimeerrors_1(self): """runtime errors test""" self.interp("zero = 0") self.interp("astr ='a string'") self.interp("atup = ('a', 'b', 11021)") self.interp("arr = range(20)") for expr, errname in (('x = 1/zero', 'ZeroDivisionError'), ('x = zero + nonexistent', 'NameError'), ('x = zero + astr', 'TypeError'), ('x = zero()', 'TypeError'), ('x = astr * atup', 'TypeError'), ('x = arr.shapx', 'AttributeError'), ('arr.shapx = 4', 'AttributeError'), ('del arr.shapx', 'KeyError'), ('x, y = atup', 'ValueError')): failed, errtype, errmsg = False, None, None # noinspection PyBroadException try: self.interp(expr, show_errors=False) except: failed = True self.assertTrue(failed) self.check_error(errname) # noinspection PyUnresolvedReferences def test_ndarrays(self): """simple ndarrays""" if HAS_NUMPY: self.interp('n = array([11, 10, 9])') self.istrue("isinstance(n, ndarray)") self.istrue("len(n) == 3") self.isvalue("n", np.array([11, 10, 9])) self.interp('n = arange(20).reshape(5, 4)') self.istrue("isinstance(n, ndarray)") self.istrue("n.shape == (5, 4)") self.interp("myx = n.shape") self.interp("n.shape = (4, 5)") self.istrue("n.shape == (4, 5)") self.interp("a = arange(20)") self.interp("gg = a[1:13:3]") self.isvalue('gg', np.array([1, 4, 7, 10])) self.interp("gg[:2] = array([0,2])") self.isvalue('gg', np.array([0, 2, 7, 10])) self.interp('a, b, c, d = gg') self.isvalue('c', 7) self.istrue('(a, b, d) == (0, 2, 10)') def test_binop(self): """test binary ops""" self.interp('a = 10.0') self.interp('b = 6.0') self.istrue("a+b == 16.0") self.isnear("a-b", 4.0) self.istrue("a/(b-1) == 2.0") self.istrue("a*b == 60.0") def test_unaryop(self): """test binary ops""" self.interp('a = -10.0') self.interp('b = -6.0') self.isnear("a", -10.0) self.isnear("b", -6.0) def test_del(self): """test del function""" self.interp('a = -10.0') self.interp('b = -6.0') self.assertTrue('a' in self.symtable) self.assertTrue('b' in self.symtable) self.interp("del a") self.interp("del b") self.assertFalse('a' in self.symtable) self.assertFalse('b' in self.symtable) # noinspection PyUnresolvedReferences def test_math1(self): """builtin math functions""" self.interp('n = sqrt(4)') self.istrue('n == 2') self.isnear('sin(pi/2)', 1) self.isnear('cos(pi/2)', 0) self.istrue('exp(0) == 1') if HAS_NUMPY: self.isnear('exp(1)', np.e) def test_namefinder(self): """test namefinder""" p = self.interp.parse('x+y+cos(z)') nf = NameFinder() nf.generic_visit(p) self.assertTrue('x' in nf.names) self.assertTrue('y' in nf.names) self.assertTrue('z' in nf.names) self.assertTrue('cos' in nf.names) def test_list_comprehension(self): """test list comprehension""" self.interp('x = [i*i for i in range(4)]') self.isvalue('x', [0, 1, 4, 9]) self.interp('x = [i*i for i in range(6) if i > 1]') self.isvalue('x', [4, 9, 16, 25]) def test_ifexp(self): """test if expressions""" self.interp('x = 2') self.interp('y = 4 if x > 0 else -1') self.interp('z = 4 if x > 3 else -1') self.isvalue('y', 4) self.isvalue('z', -1) # noinspection PyUnresolvedReferences def test_index_assignment(self): """test indexing / subscripting on assignment""" if HAS_NUMPY: self.interp('x = arange(10)') self.interp('l = [1,2,3,4,5]') self.interp('l[0] = 0') self.interp('l[3] = -1') self.isvalue('l', [0, 2, 3, -1, 5]) self.interp('l[0:2] = [-1, -2]') self.isvalue('l', [-1, -2, 3, -1, 5]) self.interp('x[1] = 99') self.isvalue('x', np.array([0, 99, 2, 3, 4, 5, 6, 7, 8, 9])) self.interp('x[0:2] = [9,-9]') self.isvalue('x', np.array([9, -9, 2, 3, 4, 5, 6, 7, 8, 9])) def test_reservedwords(self): """test reserved words""" for w in ('and', 'as', 'while', 'raise', 'else', 'class', 'del', 'def', 'import', 'None'): self.interp.error = [] # noinspection PyBroadException try: self.interp("%s= 2" % w, show_errors=False) except: pass self.check_error('SyntaxError') for w in ('True', 'False'): self.interp.error = [] self.interp("%s= 2" % w) self.check_error('SyntaxError' if PY3 else 'NameError') for w in ('eval', '__import__'): self.interp.error = [] self.interp("%s= 2" % w) self.check_error('NameError') def test_raise(self): """test raise""" self.interp("raise NameError('bob')") self.check_error('NameError', 'bob') def test_tryexcept(self): """test try/except""" self.interp(textwrap.dedent(""" x = 5 try: x = x/0 except ZeroDivisionError: print( 'Error Seen!') x = -999 """)) self.isvalue('x', -999) self.interp(textwrap.dedent(""" x = -1 try: x = x/0 except ZeroDivisionError: pass """)) self.isvalue('x', -1) self.interp(textwrap.dedent(""" x = 15 try: raise Exception() x = 20 except: pass """)) self.isvalue('x', 15) def test_tryelsefinally(self): self.interp(textwrap.dedent(""" def dotry(x, y): out, ok, clean = 0, False, False try: out = x/y except ZeroDivisionError: out = -1 else: ok = True finally: clean = True return out, ok, clean """)) self.interp("val, ok, clean = dotry(1, 2.0)") self.interp("print(ok, clean)") self.isnear("val", 0.5) self.isvalue("ok", True) self.isvalue("clean", True) self.interp("val, ok, clean = dotry(1, 0.0)") self.isvalue("val", -1) self.isvalue("ok", False) self.isvalue("clean", True) def test_function1(self): """test function definition and running""" self.interp(textwrap.dedent(""" def fcn(x, scale=2): 'test function' out = sqrt(x) if scale > 1: out = out * scale return out """)) self.interp("a = fcn(4, scale=9)") self.isvalue("a", 18) self.interp("a = fcn(9, scale=0)") self.isvalue("a", 3) self.interp("print(fcn)") self.check_output(' 5: return 1 return -1 def b(): return 2.5 def c(x=10): x = a(x=x) y = b() return x + y """ self.interp(textwrap.dedent(setup)) self.interp("o1 = c()") self.interp("o2 = c(x=0)") self.isvalue('o1', 3.5) self.isvalue('o2', 1.5) def test_astdump(self): """test ast parsing and dumping""" astnode = self.interp.parse('x = 1') self.assertTrue(isinstance(astnode, ast.Module)) self.assertTrue(isinstance(astnode.body[0], ast.Assign)) self.assertTrue(isinstance(astnode.body[0].targets[0], ast.Name)) self.assertTrue(isinstance(astnode.body[0].value, ast.Num)) self.assertTrue(astnode.body[0].targets[0].id == 'x') self.assertTrue(astnode.body[0].value.n == 1) dumped = self.interp.dump(astnode.body[0]) self.assertTrue(dumped.startswith('Assign')) # noinspection PyTypeChecker def test_safe_funcs(self): self.interp("'*'*(2<<17)") self.check_error(None) self.interp("'*'*(1+2<<17)") self.check_error('RuntimeError') self.interp("'*'*(2<<17) + '*'") self.check_error('RuntimeError') self.interp("10**10000") self.check_error(None) self.interp("10**10001") self.check_error('RuntimeError') self.interp("1<<1000") self.check_error(None) self.interp("1<<1001") self.check_error('RuntimeError') def test_safe_open(self): self.interp('open("foo1", "wb")') self.check_error('RuntimeError') self.interp('open("foo2", "rb")') self.check_error('FileNotFoundError' if PY3 else 'IOError') self.interp('open("foo3", "rb", 2<<18)') self.check_error('RuntimeError') def test_recursionlimit(self): self.interp("""def foo(): return foo()\nfoo()""") self.check_error('RecursionError' if PY3 else 'RuntimeError') def test_kaboom(self): """ test Ned Batchelder's 'Eval really is dangerous' - Kaboom test (and related tests)""" self.interp("""(lambda fc=(lambda n: [c for c in ().__class__.__bases__[0].__subclasses__() if c.__name__ == n][0]): fc("function")(fc("code")(0,0,0,0,"KABOOM",(),(),(),"","",0,""),{})() )()""") self.check_error('NotImplementedError', 'Lambda') # Safe, lambda is not supported self.interp( """[print(c) for c in ().__class__.__bases__[0].__subclasses__()]""") # Try a portion of the kaboom... if PY3: self.check_error('AttributeError', '__class__') # Safe, unsafe dunders are not supported else: self.check_error('SyntaxError') self.interp("9**9**9**9**9**9**9**9") self.check_error('RuntimeError') # Safe, safe_pow() catches this self.interp( "((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((1))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))") self.check_error('MemoryError') # Hmmm, this is caught, but its still concerning... self.interp("compile('xxx')") self.check_error('NameError') # Safe, compile() is not supported def test_exit_value(self): """test expression eval - last exp. is returned by interpreter""" z = self.interp("True") self.assertTrue(z) z = self.interp("x = 1\ny = 2\ny == x + x\n") self.assertTrue(z) z = self.interp("x = 42\nx") self.assertEqual(z, 42) self.isvalue('x', 42) z = self.interp("""def foo(): return 42\nfoo()""") self.assertEqual(z, 42) def test_removenodehandler(self): handler = self.interp.remove_nodehandler('ifexp') self.interp('testval = 300') self.interp('bogus = 3 if testval > 100 else 1') self.check_error('NotImplementedError') self.interp.set_nodehandler('ifexp', handler) self.interp('bogus = 3 if testval > 100 else 1') self.isvalue('bogus', 3) def test_get_user_symbols(self): self.interp("x = 1.1\ny = 2.5\nz = 788\n") usersyms = self.interp.user_defined_symbols() assert('x' in usersyms) assert('y' in usersyms) assert('z' in usersyms) assert('foo' not in usersyms) def test_custom_symtable(self): "test making and using a custom symbol table" if HAS_NUMPY: def cosd(x): "cos with angle in degrees" return np.cos(np.radians(x)) def sind(x): "sin with angle in degrees" return np.sin(np.radians(x)) def tand(x): "tan with angle in degrees" return np.tan(np.radians(x)) sym_table = make_symbol_table(cosd=cosd, sind=sind, tand=tand) aeval = Interpreter(symtable=sym_table) aeval("x1 = sind(30)") aeval("x2 = cosd(30)") aeval("x3 = tand(45)") x1 = aeval.symtable['x1'] x2 = aeval.symtable['x2'] x3 = aeval.symtable['x3'] assert_allclose(x1, 0.50, rtol=0.001) assert_allclose(x2, 0.866025, rtol=0.001) assert_allclose(x3, 1.00, rtol=0.001) def test_readonly_symbols(self): def foo(): return 31 usersyms = { "a": 10, "b": 11, "c": 12, "d": 13, "foo": foo, "bar": foo, "x": 5, "y": 7 } aeval = Interpreter(usersyms=usersyms, readonly_symbols={"a", "b", "c", "d", "foo", "bar"}) aeval("a = 20") aeval("def b(): return 100") aeval("c += 1") aeval("del d") aeval("def foo(): return 55") aeval("bar = None") aeval("x = 21") aeval("y += a") assert(aeval("a") == 10) assert(aeval("b") == 11) assert(aeval("c") == 12) assert(aeval("d") == 13) assert(aeval("foo()") == 31) assert(aeval("bar()") == 31) assert(aeval("x") == 21) assert(aeval("y") == 17) assert(aeval("abs(8)") == 8) assert(aeval("abs(-8)") == 8) aeval("def abs(x): return x*2") assert(aeval("abs(8)") == 16) assert(aeval("abs(-8)") == -16) aeval2 = Interpreter(builtins_readonly=True) assert(aeval2("abs(8)") == 8) assert(aeval2("abs(-8)") == 8) aeval2("def abs(x): return x*2") assert(aeval2("abs(8)") == 8) assert(aeval2("abs(-8)") == 8) def test_chained_compparisons(self): self.interp('a = 7') self.interp('b = 12') self.interp('c = 19') self.interp('d = 30') self.assertTrue(self.interp('a < b < c < d')) self.assertFalse(self.interp('a < b < c/88 < d')) self.assertFalse(self.interp('a < b < c < d/2')) def test_array_compparisons(self): if HAS_NUMPY: self.interp("sarr = arange(8)") sarr = np.arange(8) o1 = self.interp("sarr < 4.3") assert(np.all(o1 == (sarr < 4.3))) o1 = self.interp("sarr == 4") assert(np.all(o1 == (sarr == 4))) def test_minimal(self): aeval = Interpreter(builtins_readonly=True, minimal=True) aeval("a_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}") self.assertTrue(aeval("a_dict['a'] == 1")) self.assertTrue(aeval("a_dict['c'] == 3")) class TestCase2(unittest.TestCase): def test_stringio(self): """ test using stringio for output/errors """ out = StringIO() err = StringIO() intrep = Interpreter(writer=out, err_writer=err) intrep("print('out')") self.assertEqual(out.getvalue(), 'out\n') if __name__ == '__main__': pytest.main(['-v', '-x', '-s']) python-asteval-0.9.17/versioneer.py000066400000000000000000002060031356473326000173330ustar00rootroot00000000000000 # Version: 0.18 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain * Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy * [![Latest Version] (https://pypip.in/version/versioneer/badge.svg?style=flat) ](https://pypi.python.org/pypi/versioneer/) * [![Build Status] (https://travis-ci.org/warner/python-versioneer.png?branch=master) ](https://travis-ci.org/warner/python-versioneer) This is a tool for managing a recorded version number in distutils-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install * `pip install versioneer` to somewhere to your $PATH * add a `[versioneer]` section to your setup.cfg (see below) * run `versioneer install` in your source tree, commit the results ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS keyword ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes. The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. To allow `setup.py` to compute a version too, a `versioneer.py` is added to the top level of your source tree, next to `setup.py` and the `setup.cfg` that configures it. This overrides several distutils/setuptools commands to compute the version when invoked, and changes `setup.py build` and `setup.py sdist` to replace `_version.py` with a small static file that contains just the generated version data. ## Installation See [INSTALL.md](./INSTALL.md) for detailed installation instructions. ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different flavors of version information: * `['version']`: A condensed version string, rendered using the selected style. This is the most commonly used value for the project's version string. The default "pep440" style yields strings like `0.11`, `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section below for alternative styles. * `['full-revisionid']`: detailed revision identifier. For Git, this is the full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the commit date in ISO 8601 format. This will be None if the date is not available. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that this is only accurate if run in a VCS checkout, otherwise it is likely to be False or None * `['error']`: if the version string could not be computed, this will be set to a string describing the problem, otherwise it will be None. It may be useful to throw an exception in setup.py if this is set, to avoid e.g. creating tarballs with a version string of "unknown". Some variants are more useful than others. Including `full-revisionid` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. The installer adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version__ = get_versions()['version'] del get_versions ## Styles The setup.cfg `style=` configuration controls how the VCS information is rendered into a version string. The default style, "pep440", produces a PEP440-compliant string, equal to the un-prefixed tag name for actual releases, and containing an additional "local version" section with more detail for in-between builds. For Git, this is TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and that this commit is two revisions ("+2") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". Other styles are available. See [details.md](details.md) in the Versioneer source tree for descriptions. ## Debugging Versioneer tries to avoid fatal errors: if something goes wrong, it will tend to return a version of "0+unknown". To investigate the problem, run `setup.py version`, which will run the version-lookup code in a verbose mode, and will display the full contents of `get_versions()` (including the `error` string, which may help identify what went wrong). ## Known Limitations Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github [issues page](https://github.com/warner/python-versioneer/issues). ### Subprojects Versioneer has limited support for source trees in which `setup.py` is not in the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are two common reasons why `setup.py` might not be in the root: * Source trees which contain multiple subprojects, such as [Buildbot](https://github.com/buildbot/buildbot), which contains both "master" and "slave" subprojects, each with their own `setup.py`, `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also provide bindings to Python (and perhaps other langauges) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs and implementation details which frequently cause `pip install .` from a subproject directory to fail to find a correct version string (so it usually defaults to `0+unknown`). `pip install --editable .` should work correctly. `setup.py install` might work too. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. [Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/warner/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve pip to let Versioneer work correctly. Versioneer-0.16 and earlier only looked for a `.git` directory next to the `setup.cfg`, so subprojects were completely unsupported with those releases. ### Editable installs with setuptools <= 18.5 `setup.py develop` and `pip install --editable .` allow you to install a project into a virtualenv once, then continue editing the source code (and test) without re-installing after every change. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a convenient way to specify executable scripts that should be installed along with the python package. These both work as expected when using modern setuptools. When using setuptools-18.5 or earlier, however, certain operations will cause `pkg_resources.DistributionNotFound` errors when running the entrypoint script, which must be resolved by re-installing the package. This happens when the install happens with one version, then the egg_info data is regenerated while a different version is checked out. Many setup.py commands cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. [Bug #83](https://github.com/warner/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ### Unicode version strings While Versioneer works (and is continually tested) with both Python 2 and Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. Newer releases probably generate unicode version strings on py2. It's not clear that this is wrong, but it may be surprising for applications when then write these strings to a network connection or include them in bytes-oriented APIs like cryptographic checksums. [Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates this question. ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * edit `setup.cfg`, if necessary, to include any new configuration settings indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. * re-run `versioneer install` in your source tree, to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. Specifically, both are released under the Creative Commons "Public Domain Dedication" license (CC0-1.0), as described in https://creativecommons.org/publicdomain/zero/1.0/ . """ from __future__ import print_function try: import configparser except ImportError: import ConfigParser as configparser import errno import json import os import re import subprocess import sys class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. me = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(me)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(me), versioneer_py)) except NameError: pass return root def get_config_from_root(root): """Read the project setup.cfg file to determine Versioneer config.""" # This might raise EnvironmentError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.SafeConfigParser() with open(setup_cfg, "r") as f: parser.readfp(f) VCS = parser.get("versioneer", "VCS") # mandatory def get(parser, name): if parser.has_option("versioneer", name): return parser.get("versioneer", name) return None cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = get(parser, "style") or "" cfg.versionfile_source = get(parser, "versionfile_source") cfg.versionfile_build = get(parser, "versionfile_build") cfg.tag_prefix = get(parser, "tag_prefix") if cfg.tag_prefix in ("''", '""'): cfg.tag_prefix = "" cfg.parentdir_prefix = get(parser, "parentdir_prefix") cfg.verbose = get(parser, "verbose") return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" # these dictionaries contain VCS-specific tools LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode LONG_VERSION_PY['git'] = ''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.18 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%%s*" %% tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%%d" %% pieces["distance"] else: # exception #1 rendered = "0.post.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os.path.relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.18) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename): """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() except EnvironmentError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} def get_version(): """Get the short version string for this project.""" return get_versions()["version"] def get_cmdclass(): """Get the custom setuptools/distutils subclasses used by Versioneer.""" if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/warner/python-versioneer/issues/52 cmds = {} # we add "version" to both distutils and setuptools from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? try: from py2exe.distutils_buildexe import py2exe as _py2exe # py3 except ImportError: from py2exe.build_exe import py2exe as _py2exe # py2 class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ INIT_PY_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ def do_setup(): """Main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except EnvironmentError: old = "" if INIT_PY_SNIPPET not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except EnvironmentError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0 def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass()" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": errors = do_setup() errors += scan_setup_py() if errors: sys.exit(1)