How to use the boltons.typeutils.make_sentinel function in boltons

To help you get started, we’ve selected a few boltons examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mahmoud / glom / glom / matching.py View on Github external
)
        if matched:
            return target
        raise GlomMatchError("{!r} {} {!r}", lhs, _M_OP_MAP.get(op, op), rhs)

    def __repr__(self):
        if self is M:
            return "M"
        op = _M_OP_MAP.get(self.op, self.op)
        return "{!r} {} {!r}".format(self.lhs, op, self.rhs)


M = _MType(None, None, None)


_MISSING = make_sentinel('MISSING')


class Optional(object):
    """
    mark a key as optional in a dictionary

    by default all non-exact-match type keys are optional
    """
    __slots__ = ('key',)

    def __init__(self, key):
        assert _precedence(key) == 0, "key must be == match"
        self.key = key

    def glomit(self, target, scope):
        if target != self.key:
github mahmoud / glom / glom / core.py View on Github external
# call with target rather than cur,
            # because it is probably more intuitive
            # if args to the call "reset" their path
            # e.g. "T.a" should mean the same thing
            # in both of these specs: T.a and T.b(T.a)
        i += 2
    return cur


T = TType()  # target aka Mr. T aka "this"
S = TType()  # like T, but means grab stuff from Scope, not Target

_T_PATHS[T] = (T,)
_T_PATHS[S] = (S,)
UP = make_sentinel('UP')
ROOT = make_sentinel('ROOT')


def _format_invocation(name='', args=(), kwargs=None):  # pragma: no cover
    # TODO: add to boltons
    kwargs = kwargs or {}
    a_text = ', '.join([repr(a) for a in args])
    if isinstance(kwargs, dict):
        kwarg_items = kwargs.items()
    else:
        kwarg_items = kwargs
    kw_text = ', '.join(['%s=%r' % (k, v) for k, v in kwarg_items])

    star_args_text = a_text
    if star_args_text and kw_text:
        star_args_text += ', '
    star_args_text += kw_text
github securestate / king-phisher / king_phisher / server / server_rpc.py View on Github external
'server.vhost_directories',
	'server.web_root'
)
"""Configuration options that can be accessed by the client."""
CONFIG_WRITEABLE = ('beef.hook_url',)
"""Configuration options that can be changed by the client at run time."""
RPC_AUTH_HEADER = 'X-RPC-Auth'
"""The header which contains the RPC authorization / session token."""
VIEW_ROW_COUNT = 50
"""The default number of rows to return when one of the /view methods are called."""

database_tables = db_models.database_tables
graphql_schema = schema.Schema()
rpc_logger = logging.getLogger('KingPhisher.Server.RPC')

_REDACTED = boltons.typeutils.make_sentinel('REDACTED', 'REDACTED')
"""Used with :py:func:`_log_rpc_call` as a place holder for sensitive arguments such as database row values."""

class _lend_semaphore(object):
	def __init__(self, handler):
		self.handler = handler

	def __enter__(self):
		self.handler.semaphore_release()

	def __exit__(self, exc_type, exc_val, exc_tb):
		self.handler.semaphore_acquire()

def _log_rpc_call(handler_instance, function_name, *args, **kwargs):
	if not rpc_logger.isEnabledFor(logging.DEBUG):
		return
	args_repr = ', '.join(map(repr, args))
github mahmoud / glom / glom / core.py View on Github external
target, Call(cur, args, kwargs), scope)
            # call with target rather than cur,
            # because it is probably more intuitive
            # if args to the call "reset" their path
            # e.g. "T.a" should mean the same thing
            # in both of these specs: T.a and T.b(T.a)
        i += 2
    return cur


T = TType()  # target aka Mr. T aka "this"
S = TType()  # like T, but means grab stuff from Scope, not Target

_T_PATHS[T] = (T,)
_T_PATHS[S] = (S,)
UP = make_sentinel('UP')
ROOT = make_sentinel('ROOT')


def _format_invocation(name='', args=(), kwargs=None):  # pragma: no cover
    # TODO: add to boltons
    kwargs = kwargs or {}
    a_text = ', '.join([repr(a) for a in args])
    if isinstance(kwargs, dict):
        kwarg_items = kwargs.items()
    else:
        kwarg_items = kwargs
    kw_text = ', '.join(['%s=%r' % (k, v) for k, v in kwarg_items])

    star_args_text = a_text
    if star_args_text and kw_text:
        star_args_text += ', '
github mahmoud / boltons / boltons / funcutils.py View on Github external
basestring = (str, bytes)  # Python 3 compat
    _IS_PY2 = False
else:
    _IS_PY2 = True


try:
    _inspect_iscoroutinefunction = inspect.iscoroutinefunction
except AttributeError:
    # Python 3.4
    _inspect_iscoroutinefunction = lambda func: False


try:
    from boltons.typeutils import make_sentinel
    NO_DEFAULT = make_sentinel(var_name='NO_DEFAULT')
except ImportError:
    NO_DEFAULT = object()


_IS_PY35 = sys.version_info >= (3, 5)
if not _IS_PY35:
    # py35+ wants you to use signature instead, but
    # inspect_formatargspec is way simpler for what it is. Copied the
    # vendoring approach from alembic:
    # https://github.com/sqlalchemy/alembic/blob/4cdad6aec32b4b5573a2009cc356cb4b144bd359/alembic/util/compat.py#L92
    from inspect import formatargspec as inspect_formatargspec
else:
    from inspect import formatannotation

    def inspect_formatargspec(
            args, varargs=None, varkw=None, defaults=None,
github mahmoud / glom / glom / matching.py View on Github external
if not match:
            raise GlomMatchError("target did not match pattern", target, self.pattern)
        scope.update(match.groupdict())
        return target

    def __repr__(self):
        args = '(' + repr(self.pattern)
        if self.flags:
            args += ', flags=' + repr(flags)
        if self.func is not None:
            args += ', func=' + func.__name__
        args += ')'
        return "Regex" + args


DEFAULT = make_sentinel("DEFAULT")
DEFAULT.__doc__ = """
DEFAULT is used to represent keys that are not otherwise matched
in a dict in match mode
"""
DEFAULT.glomit = lambda target, scope: target


class _Bool(object):
    def __and__(self, other):
        return And(self, other)

    def __or__(self, other):
        return Or(self, other)

    def __invert__(self):
        return Not(self)
github mahmoud / boltons / boltons / cacheutils.py View on Github external
try:
    from threading import RLock
except Exception:
    class RLock(object):
        'Dummy reentrant lock for builds without threads'
        def __enter__(self):
            pass

        def __exit__(self, exctype, excinst, exctb):
            pass

try:
    from boltons.typeutils import make_sentinel
    _MISSING = make_sentinel(var_name='_MISSING')
    _KWARG_MARK = make_sentinel(var_name='_KWARG_MARK')
except ImportError:
    _MISSING = object()
    _KWARG_MARK = object()

try:
    xrange
except NameError:
    # py3
    xrange = range
    unicode, str, bytes, basestring = str, bytes, bytes, (str, bytes)

PREV, NEXT, KEY, VALUE = range(4)   # names for the link fields
DEFAULT_MAX_SIZE = 128


class LRU(dict):
github mahmoud / glom / glom / core.py View on Github external
{}
>>> target = {'a': 'a'}
>>> glom(target, spec)
{'a': 'a'}

Mostly used to drop keys from dicts (as above) or filter objects from
lists.

.. note::

   SKIP was known as OMIT in versions 18.3.1 and prior. Versions 19+
   will remove the OMIT alias entirely.
"""
OMIT = SKIP  # backwards compat, remove in 19+

STOP = make_sentinel('STOP')
STOP.__doc__ = """
The ``STOP`` singleton can be used to halt iteration of a list or
execution of a tuple of subspecs.

>>> target = range(10)
>>> spec = [lambda x: x if x < 5 else STOP]
>>> glom(target, spec)
[0, 1, 2, 3, 4]
"""

LAST_CHILD_SCOPE = make_sentinel('LAST_CHILD_SCOPE')
LAST_CHILD_SCOPE.__doc__ = """
Marker that can be used by parents to keep track of the last child
scope executed.  Useful for "lifting" results out of child scopes
for scopes that want to chain the scopes of their children together
similar to tuple.
github mahmoud / boltons / boltons / cacheutils.py View on Github external
from operator import attrgetter

try:
    from threading import RLock
except Exception:
    class RLock(object):
        'Dummy reentrant lock for builds without threads'
        def __enter__(self):
            pass

        def __exit__(self, exctype, excinst, exctb):
            pass

try:
    from boltons.typeutils import make_sentinel
    _MISSING = make_sentinel(var_name='_MISSING')
    _KWARG_MARK = make_sentinel(var_name='_KWARG_MARK')
except ImportError:
    _MISSING = object()
    _KWARG_MARK = object()

try:
    xrange
except NameError:
    # py3
    xrange = range
    unicode, str, bytes, basestring = str, bytes, bytes, (str, bytes)

PREV, NEXT, KEY, VALUE = range(4)   # names for the link fields
DEFAULT_MAX_SIZE = 128