本文整理汇总了Python中lexicon.Lexicon.alias方法的典型用法代码示例。如果您正苦于以下问题:Python Lexicon.alias方法的具体用法?Python Lexicon.alias怎么用?Python Lexicon.alias使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lexicon.Lexicon
的用法示例。
在下文中一共展示了Lexicon.alias方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Collection
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
class Collection(object):
def __init__(self):
self.tasks = Lexicon()
self.default = None
def add_task(self, name, task, aliases=(), default=False):
"""
Adds callable object ``task`` to this collection under name ``name``.
If ``aliases`` is given, will be used to set up additional aliases for
this task.
``default`` may be set to ``True`` to set the task as this collection's
default invocation.
"""
self.tasks[name] = task
for alias in aliases:
self.tasks.alias(alias, to=name)
if default:
if self.default:
msg = "'%s' cannot be the default because '%s' already is!"
raise ValueError(msg % (name, self.default))
self.default = name
def __getitem__(self, name=None):
"""
Returns task named ``name``. Honors aliases.
If this collection has a default task, it is returned when ``name`` is
empty or ``None``. If empty input is given and no task has been
selected as the default, ValueError will be raised.
"""
if not name:
if self.default:
return self[self.default]
else:
raise ValueError("This collection has no default task.")
return self.tasks[name]
def to_contexts(self):
"""
Returns all contained tasks and subtasks as a list of parser contexts.
"""
result = []
for name, task in self.tasks.iteritems():
context = Context(name=name, aliases=task.aliases)
argspec = task.argspec
for name, default in argspec.iteritems():
# Handle arg options
opts = {}
if default is not None:
opts['kind'] = type(default)
# Handle aliases (auto shortflags, etc)
names = [name]
names.extend(argspec.aliases_of(name))
# Create/add the argument
context.add_arg(names=names, **opts)
result.append(context)
return result
示例2: dir_only_shows_real_keys
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
def dir_only_shows_real_keys(self):
"dir() only shows real keys-as-attrs, not aliases"
a = Lexicon({'key1': 'val1', 'key2': 'val2'})
a.alias('myalias', 'key1')
assert 'key1' in dir(a)
assert 'key2' in dir(a)
assert 'myalias' not in dir(a)
示例3: argspec
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
def argspec(self):
spec = inspect.getargspec(self.body)
# Associate default values with their respective arg names
if spec.defaults is not None:
ret = Lexicon(zip(spec.args[-len(spec.defaults):], spec.defaults))
else:
ret = Lexicon()
# Pull in args that have no default values
ret.update((x, None) for x in spec.args if x not in ret)
# Handle auto short flags
if self.auto_shortflags:
for name in ret:
alias = None
for char in name:
if not (char == name or char in ret):
alias = char
break
if alias:
ret.alias(alias, to=name)
return ret
示例4: Parser
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
class Parser(object):
def __init__(self, contexts=(), initial=None):
self.initial = initial
self.contexts = Lexicon()
for context in contexts:
debug("Adding %s" % context)
if not context.name:
raise ValueError("Non-initial contexts must have names.")
exists = "A context named/aliased %r is already in this parser!"
if context.name in self.contexts:
raise ValueError(exists % context.name)
self.contexts[context.name] = context
for alias in context.aliases:
if alias in self.contexts:
raise ValueError(exists % alias)
self.contexts.alias(alias, to=context.name)
def parse_argv(self, argv):
"""
Parse an argv-style token list ``argv``.
Returns a list of ``Context`` objects matching the order they were
found in the ``argv`` and containing ``Argument`` objects with updated
values based on any flags given.
Assumes any program name has already been stripped out. Good::
Parser(...).parse_argv(['--core-opt', 'task', '--task-opt'])
Bad::
Parser(...).parse_argv(['invoke', '--core-opt', ...])
"""
machine = ParseMachine(initial=self.initial, contexts=self.contexts)
for token in argv:
machine.handle(token)
machine.finish()
return machine.result
示例5: Collection
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
class Collection(object):
def __init__(self):
self.tasks = Lexicon()
self.default = None
def add_task(self, name, task, aliases=(), default=False):
"""
Adds callable object ``task`` to this collection under name ``name``.
If ``aliases`` is given, will be used to set up additional aliases for
this task.
``default`` may be set to ``True`` to set the task as this collection's
default invocation.
"""
self.tasks[name] = task
for alias in aliases:
self.tasks.alias(alias, to=name)
if default:
if self.default:
msg = "'%s' cannot be the default because '%s' already is!"
raise ValueError(msg % (name, self.default))
self.default = name
def get(self, name=None):
"""
Returns task named ``name``. Honors aliases.
If this collection has a default task, it is returned when ``name`` is
empty or ``None``. If empty input is given and no task has been
selected as the default, ValueError will be raised.
"""
if not name:
if self.default:
return self.get(self.default)
else:
raise ValueError("This collection has no default task.")
return self.tasks[name]
示例6: aliased_real_attributes_do_not_override_real_attributes
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
def aliased_real_attributes_do_not_override_real_attributes(self):
lex = Lexicon()
lex.alias('get', to='notget')
lex.notget = 'value'
assert callable(lex.get)
assert lex.get != 'value'
示例7: aliases_appear_in_attributes
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
def aliases_appear_in_attributes(self):
lex = Lexicon()
lex.alias('foo', to='bar')
lex.foo = 'value'
assert lex.foo == lex.bar == lex['foo'] == lex['bar'] == 'value'
示例8: aliases_work
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
def aliases_work(self):
lex = Lexicon()
lex.alias('foo', to='bar')
lex['bar'] = 'value'
assert lex['foo'] == lex['bar'] == 'value'
示例9: aliases_appear_in_attributes
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
def aliases_appear_in_attributes(self):
l = Lexicon()
l.alias('foo', to='bar')
l.foo = 'value'
assert l.foo == l.bar == l['foo'] == l['bar'] == 'value'
示例10: aliases_work
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
def aliases_work(self):
l = Lexicon()
l.alias('foo', to='bar')
l['bar'] = 'value'
assert l['foo'] == l['bar'] == 'value'
示例11: Context
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
class Context(object):
"""
Parsing context with knowledge of flags & their format.
Generally associated with the core program or a task.
When run through a parser, will also hold runtime values filled in by the
parser.
"""
def __init__(self, name=None, aliases=(), args=()):
"""
Create a new ``Context`` named ``name``, with ``aliases``.
``name`` is optional, and should be a string if given. It's used to
tell Context objects apart, and for use in a Parser when determining
what chunk of input might belong to a given Context.
``aliases`` is also optional and should be an iterable containing
strings. Parsing will honor any aliases when trying to "find" a given
context in its input.
May give one or more ``args``, which is a quick alternative to calling
``for arg in args: self.add_arg(arg)`` after initialization.
"""
self.args = Lexicon()
self.flags = Lexicon()
self.name = name
self.aliases = aliases
for arg in args:
self.add_arg(arg)
def __str__(self):
aliases = (" (%s)" % ', '.join(self.aliases)) if self.aliases else ""
name = (" %s%s" % (self.name, aliases)) if self.name else ""
return "Context%s: %r" % (name, self.args)
def add_arg(self, *args, **kwargs):
"""
Adds given ``Argument`` (or constructor args for one) to this context.
The Argument in question is added to two dict attributes:
* ``args``: "normal" access, i.e. the given names are directly exposed
as keys.
* ``flags``: "flaglike" access, i.e. the given names are translated
into CLI flags, e.g. ``"foo"`` is accessible via ``flags['--foo']``.
"""
# Normalize
if len(args) == 1 and isinstance(args[0], Argument):
arg = args[0]
else:
arg = Argument(*args, **kwargs)
# Test
for name in arg.names:
if name in self.args:
msg = "Tried to add an argument named %r but one already exists!"
raise ValueError(msg % name)
# Add
main = arg.names[0]
self.args[main] = arg
self.flags[to_flag(main)] = arg
for name in arg.names[1:]:
self.args.alias(name, to=main)
self.flags.alias(to_flag(name), to=to_flag(main))
示例12: Parser
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
class Parser(object):
"""
Create parser conscious of ``contexts`` and optional ``initial`` context.
``contexts`` should be an iterable of ``Context`` instances which will be
searched when new context names are encountered during a parse. These
Contexts determine what flags may follow them, as well as whether given
flags take values.
``initial`` is optional and will be used to determine validity of "core"
options/flags at the start of the parse run, if any are encountered.
``ignore_unknown`` determines what to do when contexts are found which do
not map to any members of ``contexts``. By default it is ``False``, meaning
any unknown contexts result in a parse error exception. If ``True``,
encountering an unknown context halts parsing and populates the return
value's ``.unparsed`` attribute with the remaining parse tokens.
"""
def __init__(self, contexts=(), initial=None, ignore_unknown=False):
self.initial = initial
self.contexts = Lexicon()
self.ignore_unknown = ignore_unknown
for context in contexts:
debug("Adding {0}".format(context))
if not context.name:
raise ValueError("Non-initial contexts must have names.")
exists = "A context named/aliased {0!r} is already in this parser!"
if context.name in self.contexts:
raise ValueError(exists.format(context.name))
self.contexts[context.name] = context
for alias in context.aliases:
if alias in self.contexts:
raise ValueError(exists.format(alias))
self.contexts.alias(alias, to=context.name)
def parse_argv(self, argv):
"""
Parse an argv-style token list ``argv``.
Returns a list of ``Context`` objects matching the order they were
found in the ``argv`` and containing ``Argument`` objects with updated
values based on any flags given.
Assumes any program name has already been stripped out. Good::
Parser(...).parse_argv(['--core-opt', 'task', '--task-opt'])
Bad::
Parser(...).parse_argv(['invoke', '--core-opt', ...])
"""
machine = ParseMachine(initial=self.initial, contexts=self.contexts,
ignore_unknown=self.ignore_unknown)
# FIXME: Why isn't there str.partition for lists? There must be a
# better way to do this. Split argv around the double-dash remainder
# sentinel.
debug("Starting argv: {0!r}".format(argv,))
try:
ddash = argv.index('--')
except ValueError:
ddash = len(argv) # No remainder == body gets all
body = argv[:ddash]
remainder = argv[ddash:][1:] # [1:] to strip off remainder itself
if remainder:
debug("Remainder: argv[{0!r}:][1:] => {1!r}".format(
ddash, remainder
))
for index, token in enumerate(body):
# Handle non-space-delimited forms, if not currently expecting a
# flag value and still in valid parsing territory (i.e. not in
# "unknown" state which implies store-only)
if not machine.waiting_for_flag_value and is_flag(token) \
and not machine.result.unparsed:
orig = token
# Equals-sign-delimited flags, eg --foo=bar or -f=bar
if '=' in token:
token, _, value = token.partition('=')
debug("Splitting x=y expr {0!r} into tokens {1!r} and {2!r}".format( # noqa
orig, token, value))
body.insert(index + 1, value)
# Contiguous boolean short flags, e.g. -qv
elif not is_long_flag(token) and len(token) > 2:
full_token = token[:]
rest, token = token[2:], token[:2]
err = "Splitting {0!r} into token {1!r} and rest {2!r}"
debug(err.format(full_token, token, rest))
# Handle boolean flag block vs short-flag + value. Make
# sure not to test the token as a context flag if we've
# passed into 'storing unknown stuff' territory (e.g. on a
# core-args pass, handling what are going to be task args)
have_flag = (token in machine.context.flags
and machine.current_state != 'unknown')
if have_flag and machine.context.flags[token].takes_value:
debug("{0!r} is a flag for current context & it takes a value, giving it {1!r}".format(token, rest)) # noqa
body.insert(index + 1, rest)
else:
rest = ['-{0}'.format(x) for x in rest]
debug("Splitting multi-flag glob {0!r} into {1!r} and {2!r}".format( # noqa
orig, token, rest))
for item in reversed(rest):
#.........这里部分代码省略.........
示例13: Parser
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
class Parser(object):
"""
Create parser conscious of ``contexts`` and optional ``initial`` context.
``contexts`` should be an iterable of ``Context`` instances which will be
searched when new context names are encountered during a parse. These
Contexts determine what flags may follow them, as well as whether given
flags take values.
``initial`` is optional and will be used to determine validity of "core"
options/flags at the start of the parse run, if any are encountered.
``ignore_unknown`` determines what to do when contexts are found which do
not map to any members of ``contexts``. By default it is ``False``, meaning
any unknown contexts result in a parse error exception. If ``True``,
encountering an unknown context halts parsing and populates the return
value's ``.unparsed`` attribute with the remaining parse tokens.
.. versionadded:: 1.0
"""
def __init__(self, contexts=(), initial=None, ignore_unknown=False):
self.initial = initial
self.contexts = Lexicon()
self.ignore_unknown = ignore_unknown
for context in contexts:
debug("Adding {}".format(context))
if not context.name:
raise ValueError("Non-initial contexts must have names.")
exists = "A context named/aliased {!r} is already in this parser!"
if context.name in self.contexts:
raise ValueError(exists.format(context.name))
self.contexts[context.name] = context
for alias in context.aliases:
if alias in self.contexts:
raise ValueError(exists.format(alias))
self.contexts.alias(alias, to=context.name)
def parse_argv(self, argv):
"""
Parse an argv-style token list ``argv``.
Returns a list (actually a subclass, `.ParseResult`) of
`.ParserContext` objects matching the order they were found in the
``argv`` and containing `.Argument` objects with updated values based
on any flags given.
Assumes any program name has already been stripped out. Good::
Parser(...).parse_argv(['--core-opt', 'task', '--task-opt'])
Bad::
Parser(...).parse_argv(['invoke', '--core-opt', ...])
:param argv: List of argument string tokens.
:returns:
A `.ParseResult` (a ``list`` subclass containing some number of
`.ParserContext` objects).
.. versionadded:: 1.0
"""
machine = ParseMachine(
initial=self.initial,
contexts=self.contexts,
ignore_unknown=self.ignore_unknown,
)
# FIXME: Why isn't there str.partition for lists? There must be a
# better way to do this. Split argv around the double-dash remainder
# sentinel.
debug("Starting argv: {!r}".format(argv))
try:
ddash = argv.index("--")
except ValueError:
ddash = len(argv) # No remainder == body gets all
body = argv[:ddash]
remainder = argv[ddash:][1:] # [1:] to strip off remainder itself
if remainder:
debug(
"Remainder: argv[{!r}:][1:] => {!r}".format(ddash, remainder)
)
for index, token in enumerate(body):
# Handle non-space-delimited forms, if not currently expecting a
# flag value and still in valid parsing territory (i.e. not in
# "unknown" state which implies store-only)
# NOTE: we do this in a few steps so we can
# split-then-check-validity; necessary for things like when the
# previously seen flag optionally takes a value.
mutations = []
orig = token
if is_flag(token) and not machine.result.unparsed:
# Equals-sign-delimited flags, eg --foo=bar or -f=bar
if "=" in token:
token, _, value = token.partition("=")
msg = "Splitting x=y expr {!r} into tokens {!r} and {!r}"
debug(msg.format(orig, token, value))
mutations.append((index + 1, value))
# Contiguous boolean short flags, e.g. -qv
elif not is_long_flag(token) and len(token) > 2:
full_token = token[:]
#.........这里部分代码省略.........
示例14: Parser
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
class Parser(object):
"""
Create parser conscious of ``contexts`` and optional ``initial`` context.
``contexts`` should be an iterable of ``Context`` instances which will be
searched when new context names are encountered during a parse. These
Contexts determine what flags may follow them, as well as whether given
flags take values.
``initial`` is optional and will be used to determine validity of "core"
options/flags at the start of the parse run, if any are encountered.
``ignore_unknown`` determines what to do when contexts are found which do
not map to any members of ``contexts``. By default it is ``False``, meaning
any unknown contexts result in a parse error exception. If ``True``,
encountering an unknown context halts parsing and populates the return
value's ``.unparsed`` attribute with the remaining parse tokens.
"""
def __init__(self, contexts=(), initial=None, ignore_unknown=False):
self.initial = initial
self.contexts = Lexicon()
self.ignore_unknown = ignore_unknown
for context in contexts:
debug("Adding %s" % context)
if not context.name:
raise ValueError("Non-initial contexts must have names.")
exists = "A context named/aliased %r is already in this parser!"
if context.name in self.contexts:
raise ValueError(exists % context.name)
self.contexts[context.name] = context
for alias in context.aliases:
if alias in self.contexts:
raise ValueError(exists % alias)
self.contexts.alias(alias, to=context.name)
def parse_argv(self, argv):
"""
Parse an argv-style token list ``argv``.
Returns a list of ``Context`` objects matching the order they were
found in the ``argv`` and containing ``Argument`` objects with updated
values based on any flags given.
Assumes any program name has already been stripped out. Good::
Parser(...).parse_argv(['--core-opt', 'task', '--task-opt'])
Bad::
Parser(...).parse_argv(['invoke', '--core-opt', ...])
"""
machine = ParseMachine(initial=self.initial, contexts=self.contexts,
ignore_unknown=self.ignore_unknown)
# FIXME: Why isn't there str.partition for lists? There must be a
# better way to do this. Split argv around the double-dash remainder
# sentinel.
debug("Starting argv: %r" % (argv,))
try:
ddash = argv.index('--')
except ValueError:
ddash = len(argv) # No remainder == body gets all
body = argv[:ddash]
remainder = argv[ddash:][1:] # [1:] to strip off remainder itself
if remainder:
debug("Remainder: argv[%r:][1:] => %r" % (ddash, remainder))
for index, token in enumerate(body):
# Handle non-space-delimited forms, if not currently expecting a
# flag value.
if not machine.waiting_for_flag_value and token.startswith('-'):
orig = token
# Equals-sign-delimited flags, eg --foo=bar or -f=bar
if '=' in token:
token, _, value = token.partition('=')
debug("Splitting %r into tokens %r and %r" % (orig, token, value))
body.insert(index + 1, value)
# Contiguous boolean short flags, e.g. -qv
elif not token.startswith('--') and len(token) > 2:
rest, token = token[2:], token[:2]
# Handle boolean flag block vs short-flag + value
have_flag = token in machine.context.flags
if have_flag and machine.context.flags[token].takes_value:
body.insert(index + 1, rest)
else:
rest = map(lambda x: '-%s' % x, rest)
debug("Splitting %r into %r and %r" % (orig, token, rest))
for item in reversed(rest):
body.insert(index + 1, item)
machine.handle(token)
machine.finish()
result = machine.result
result.remainder = ' '.join(remainder)
return result
示例15: ParserContext
# 需要导入模块: from lexicon import Lexicon [as 别名]
# 或者: from lexicon.Lexicon import alias [as 别名]
class ParserContext(object):
"""
Parsing context with knowledge of flags & their format.
Generally associated with the core program or a task.
When run through a parser, will also hold runtime values filled in by the
parser.
"""
def __init__(self, name=None, aliases=(), args=()):
"""
Create a new ``ParserContext`` named ``name``, with ``aliases``.
``name`` is optional, and should be a string if given. It's used to
tell ParserContext objects apart, and for use in a Parser when
determining what chunk of input might belong to a given ParserContext.
``aliases`` is also optional and should be an iterable containing
strings. Parsing will honor any aliases when trying to "find" a given
context in its input.
May give one or more ``args``, which is a quick alternative to calling
``for arg in args: self.add_arg(arg)`` after initialization.
"""
self.args = Lexicon()
self.positional_args = []
self.flags = Lexicon()
self.inverse_flags = {} # No need for Lexicon here
self.name = name
self.aliases = aliases
for arg in args:
self.add_arg(arg)
def __repr__(self):
aliases = ""
if self.aliases:
aliases = " ({0})".format(', '.join(self.aliases))
name = (" {0!r}{1}".format(self.name, aliases)) if self.name else ""
args = (": {0!r}".format(self.args)) if self.args else ""
return "<parser/Context{0}{1}>".format(name, args)
def add_arg(self, *args, **kwargs):
"""
Adds given ``Argument`` (or constructor args for one) to this context.
The Argument in question is added to the following dict attributes:
* ``args``: "normal" access, i.e. the given names are directly exposed
as keys.
* ``flags``: "flaglike" access, i.e. the given names are translated
into CLI flags, e.g. ``"foo"`` is accessible via ``flags['--foo']``.
* ``inverse_flags``: similar to ``flags`` but containing only the
"inverse" versions of boolean flags which default to True. This
allows the parser to track e.g. ``--no-myflag`` and turn it into a
False value for the ``myflag`` Argument.
"""
# Normalize
if len(args) == 1 and isinstance(args[0], Argument):
arg = args[0]
else:
arg = Argument(*args, **kwargs)
# Uniqueness constraint: no name collisions
for name in arg.names:
if name in self.args:
msg = "Tried to add an argument named {0!r} but one already exists!" # noqa
raise ValueError(msg.format(name))
# First name used as "main" name for purposes of aliasing
main = arg.names[0] # NOT arg.name
self.args[main] = arg
# Note positionals in distinct, ordered list attribute
if arg.positional:
self.positional_args.append(arg)
# Add names & nicknames to flags, args
self.flags[to_flag(main)] = arg
for name in arg.nicknames:
self.args.alias(name, to=main)
self.flags.alias(to_flag(name), to=to_flag(main))
# Add attr_name to args, but not flags
if arg.attr_name:
self.args.alias(arg.attr_name, to=main)
# Add to inverse_flags if required
if arg.kind == bool and arg.default is True:
# Invert the 'main' flag name here, which will be a dashed version
# of the primary argument name if underscore-to-dash transformation
# occurred.
inverse_name = to_flag("no-{0}".format(main))
self.inverse_flags[inverse_name] = to_flag(main)
@property
def needs_positional_arg(self):
return any(x.value is None for x in self.positional_args)
@property
def as_kwargs(self):
"""
This context's arguments' values keyed by their ``.name`` attribute.
Results in a dict suitable for use in Python contexts, where e.g. an
arg named ``foo-bar`` becomes accessible as ``foo_bar``.
"""
#.........这里部分代码省略.........