em¶
A system for processing Python via markup embeded in text.
- class em.BackquoteToken(current, config, first)¶
A backquote markup:
@`...`
- exception em.BreakFlow¶
- class em.CodedToken(current, config, first)¶
The abstract base class for a token that supports codings.
- class em.Command(noun)¶
A generic high-level processing command.
- process(interp, n)¶
Run the command.
- class em.CommentToken(current, config, first)¶
The abstract base class for the comment tokens.
- exception em.CompatibilityError(*args, **kwargs)¶
- class em.Configuration(**kwargs)¶
The configuration encapsulates all the defaults and parameterized behavior of an interpreter. When created, an interpreter is assigned a configuration; multiple configurations can be shared between different interpreters. To override the defaults of an interpreter, create a Configuration instance and then modify its attributes.
- adjustFactory()¶
Adjust the factory to take into account a non-default prefix.
- baseException¶
alias of
BaseException
- calculateIconsSignature(icons=None)¶
Calculate a signature of the icons dict. If the value changes, it’s likely (but not certain) that the underlying dict has changed. The signature will always differ from None.
- check(inputFilename, outputFilename)¶
Do a sanity check on the configuration settings.
- checkProxy(abandonedIsError=True)¶
Check whether a proxy is installed. Returns the current reference count (positive means one is installed), None (for no proxy installed), or 0 if the proxy has been abandoned. Thus, true means a proxy is installed, false means one isn’t. If abandonIsError is true, raise instead of returning 0 on abandonment.
- clone(deep=False)¶
Create a distinct copy of this configuration. Make it deep if desired.
- createFactory(tokens=None)¶
Create a token factory and return it.
- createFinder()¶
Create a new finder object, ready for installation.
- declare(name, specs, initial, description, none=False, helpFunction=None)¶
Declare the configuration attribute.
- define(name, specs, value, description, none=False, env=None, func=None, blank=None, invert=False, helpFunction=None)¶
Define a configuration attribute with the given name, type specification, initial value, and description. If none is true, None is a legal value. Also, allow an optional corresponding environment variable, and, if present, an optional blank variable to set the value to if the environment variable is defined but is blank. If both env and func are present, call the function to set the environment variable. Finally, if invert is true, invert the (bool) environment variable. Additionally, if the type specification is or contains toString, convert the value to a proper string.
- disableBinary()¶
Disable binary/Unicode support for this configuration.
- enableBinary(major=None, minor=None)¶
Enable binary/Unicode file open support. This is needed in Python 2.x for Unicode support. If major/minor is present, only enable it implicitly if this is in fact Python 2.x.
- environment(name, default=None, blank=None)¶
Get the value of the given environment variable, or default if it is not set. If a variable is set to an empty value and blank is non-None, return blank instead.
- errorToExitCode(error)¶
Determine the exit code (can be a string) from the error. If the error is None, then it is success.
- escaped(ord, prefix='\\')¶
Write a valid Python string escape sequence for the given character ordinal.
- static evocare(increment=0, ignore=True)¶
Try to call the EmPy special method on the proxy with the given increment argument and return the resulting count value. If the magic method is not present (no proxy installed) and ignore is true (default), return None; otherwise, raise. Exodus is four as one!
- static finder(object=<module 'sys' (built-in)>)¶
Find the meta path finder for this Python interpreter session, if there is one.
- formatError(error, prefix=None, suffix=None)¶
Format an error into a string for printing.
- get(name, default=None)¶
Get this (valid, existing) configuration attribute.
- getDefaultEncoding(default='unknown')¶
What is the default encoding?
- getFactory(tokens=None, force=False)¶
Get a factory (creating one if one has not yet been created). If force is true, always create a new one.
- has(name)¶
Is this name a valid configuration attribute?
- hasBinary()¶
Is binary/Unicode file open support enabled?
- hasDefaultPrefix()¶
Is this configuration’s prefix the default or non-existent?
- hasEnvironment(name)¶
Is the current environment variable defined in the environment? The value does not matter.
- initialize()¶
Setup the declarations and definitions for the defined attributes.
- initializeEmojiModules(moduleNames=None)¶
Initialize the emoji modules. If moduleNames is not specified, check the defaults. Idempotent.
- installFinder(index=None, dryRun=False)¶
Install EmPy module support, if possible. Mark a flag the first time this is called so it’s only installed once, if ever. Idempotent.
- installProxy(output)¶
Install a proxy if necessary around the given output, wrapped to be uncloseable. Return the wrapped object (not the proxy).
- isDefaultEncodingErrors(encoding=None, errors=None, asInput=True)¶
Are both of the encoding/errors combinations the default? If either passed value is None the value in this configuration is what is checked. Check for input if asInput is true; otherwise check output.
- isExitError(error)¶
Is this error a SystemExit?
- isInitialized()¶
Is this configuration initialized and ready for use?
- isNotAnError(error)¶
Is this error None (no error) or does it indicate a successful exit?
- isSuccessCode(code)¶
Does this exit code indicate success?
- load(filename, required=None)¶
Update the configuration by loading from a resource file. If required is true, raise an exception; if false, ignore; if None, use the default in this configuration. Return whether or not the load succeeded.
- open(filename, mode=None, buffering=-1, encoding=None, errors=None, expand=None)¶
Open a new file, handling whether or not binary (Unicode) should be employed. Raise if the selection cannot be complied with. Arguments:
filename: The filename to open;
mode: The file open mode, None for read;
buffering: The buffering setting (int);
encoding: The encoding to use, None for default;
errors: The error handler to use, None for default;
expand: Expand user constructions? (~ and ~user)
- path(path, required=None)¶
Attempt to load several resource paths, either as a list of paths or a delimited string of paths. If required is true, raise an exception; if false, ignore; if None, use the default in this configuration.
- static proxy(object=<module 'sys' (built-in)>)¶
Find the proxy for this Python interpreter session, or None.
- recode(result, encoding=None)¶
Convert a lookup table entry into a string. A value can be a string itself, an integer corresponding to a code point, or a 2-tuple, the first value of which is one of the above (the second is a description). If the encoding is provided, use that to convert bytes objects; otherwise, use the output encoding.
- reconfigure(file, buffering=-1, encoding=None, errors=None)¶
Reconfigure an existing file (e.g., sys.stdout)) with the same arguments as open.
- renderContext(context)¶
Render the context as a string according to this configuration.
- resetFactory()¶
Clear the current factory.
- run(statements)¶
Run some configuration variable assignment statements.
- set(name, value)¶
Set the (valid) configuration attribute, checking its type if necessary.
- setBuffering(name)¶
Set the buffering by name or value.
- setContextFormat(rawFormat)¶
Set the context format, auto-detecting which mechanism to use.
- signIcons(icons=None)¶
Sign the icons dict.
- significatorFor(key)¶
Return the significator name for this key.
- significatorRe(flags=RegexFlag.None, baseFlags=RegexFlag.VERBOSE)¶
Return a regular expression object with the given flags that is suitable for parsing significators.
- significatorReString()¶
Return a string that can be compiled into a regular expression representing a significator. If multi is true, it will match multiline significators.
- substituteEmoji(text)¶
Substitute emojis from the provided string. Return the resulting substitution or None.
- transmogrifyIcons(icons=None)¶
Process the icons and make sure any keys’ prefixes are backfilled with Nones. Call this method after modifying icons.
- uninstallFinder(tag=None)¶
Uninstall any module meta path finder for EmPy support, either by tag (if not None), or all. Idempotent.
- uninstallProxy()¶
Uninstall a proxy if necessary.
- update(**kwargs)¶
Update the configuration by keyword arguments.
- validateIcons(icons=None)¶
If the icons have not been transmogrified yet, do so and store their signature for future reference.
- exception em.ConfigurationError(*args, **kwargs)¶
- exception em.ConfigurationFileNotFoundError(*args, **kwargs)¶
- exception em.ConsistencyError(*args, **kwargs)¶
- class em.Context(name, line, column, chars=0, startingLine=None, startingColumn=None)¶
A simple interpreter context, storing only the current data. It is not intended to be modified.
- accumulate()¶
Accumulate the pending information and incorporate it into the total.
- render(format, useFormatMethod=None)¶
Render the context with the given format. If useFormatMethod is true, use the format method; if false, use the % operator. If useFormatMethod is None, try to trivially auto-detect given the format.
- reset()¶
Reset the context to the start.
- restore(other, strict=False)¶
Restore from another context.
- save(strict=False)¶
Take a snapshot of the current context.
- track(string, start, end)¶
Track the information for the substring in [start, end) in the context and mark it pending.
- class em.ContextLineToken(current, config, first)¶
A context line change markup:
@!...
- class em.ContextNameToken(current, config, first)¶
A context name change markup:
@?...
- class em.ContextToken(current, config, first)¶
A base class for the context tokens.
- exception em.ContinueFlow¶
- class em.ControlToken(current, config, first)¶
A control markup:
@[...]
- class Chain(head, tail)¶
A chain of tokens with a starting token and the rest that follow.
- build(allowed)¶
Process the list of subtokens and divide it up into a list of chains, returning that list. Allowed specifies a list of the only secondary markup types which are allowed.
- subrun(tokens, interp, locals)¶
Execute a list of tokens.
- subscan(scanner, primary)¶
Do a subscan for contained tokens.
- class em.Core(**kwargs)¶
A core encapsulates the functionality of the underlying language (Python by default). To create an object where this these are native methods to that class, derive a class from Core but do not call its constructor.
- define(signature, definition, locals=None)¶
Implement @[def …] markup; return value ignored.
- evaluate(code, globals, locals=None)¶
Evaluate an expression and return it.
- execute(code, globals, locals=None)¶
Execute a statement(s); return value ignored.
- match(expression, cases, locals=None)¶
Implement @[match …] markup; return value ignored.
- quote(code)¶
Find the right quote for this code.
- serialize(thing)¶
Return the string representation of an object.
- exception em.CoreError(*args, **kwargs)¶
- class em.DelegatingFile(delegate)¶
A simple class which wraps around a delegate file-like object and lets everything through.
- unlink()¶
Unlink from the delegate.
- class em.DiacriticToken(current, config, first)¶
A diacritic markup:
@^...
- class em.DisableToken(current, config, first)¶
An disable output markup:
@- ... NL
- class em.Diversion(name)¶
The representation of an active diversion. Diversions act as (writable) file objects, and then can be recalled either as pure strings or (readable) file objects.
- asFile()¶
Return the diversion as a file.
- asString()¶
Return the diversion as a string.
- preferFile()¶
Would this particular diversion prefer to be treated as a file (true) or a string (false)? This allows future optimization of diversions into actual files if they get overly large.
- spool(sink, chunkSize=16384)¶
Spool the diversion to the given sink.
- exception em.DiversionError(*args, **kwargs)¶
- class em.DocumentCommand(noun)¶
Read and execute an EmPy document.
- process(interp, n)¶
Run the command.
- class em.EmojiModuleInfo(name, attribute, format, capitalization, delimiters, *extra)¶
The abstraction of an emoji module that may or may not be available for usage.
- initialize()¶
Attempt to initialize this emoji module. Set ok to true if successful.
- substitute(text)¶
Substitute text using this module. Return None if unsuccessful.
- class em.EmojiToken(current, config, first)¶
An emoji markup:
@:...:
- class em.EnableToken(current, config, first)¶
An enable output markup:
@+ ... NL
- exception em.Error(*args, **kwargs)¶
- class em.EscapeToken(current, config, first)¶
An escape markup:
@\...
- string()¶
Return a general hexadecimal escape sequence rather than the exact one that was input.
- em.ExecCommand¶
alias of
ExecuteCommand
- class em.ExecutionToken(current, config, first)¶
The abstract base class for execution tokens (expressions, statements, controls, etc.)
- class em.ExpansionToken(current, config, first)¶
A token that involves an expansion.
- class em.ExpressionToken(current, config, first)¶
An expression markup:
@(...)
- class em.Extension(mapping=None, **kwargs)¶
An extension plugin that the interpreter will defer to for non-standard markup.
- exception em.ExtensionError(*args, **kwargs)¶
- class em.ExtensionToken(current, config, first)¶
An extension markup, used for all customizable markup:
@((...))
,@[[...]]
,@{{...}}
,@<...>
, etc.
- class em.Factory(tokens)¶
Turn a first character sequence into a token class. Token classes have a first attribute which is either None to indicate whatever the current prefix is; a string in angle brackets to indicate a special test; or a character sequence; or a list of character sequences. Token classes are then retrieved by lookup table, or special test. Initialize this meta-factory with a list of factory classes and it will automatically setup the lookup tables based on their first attributes.
- addToken(token, protect=False)¶
Add another token class to the factory.
- addendum(first)¶
An optional addendum about unsupported markup sequence (for compatibility or future notes).
- adjust(config)¶
Adjust this factory to swap the markup for a non-default prefix, if necessary.
- removeToken(first)¶
Remove token(s) from the mapping by first, which can be a string first or a list of strings firsts.
- class em.File¶
An abstract filelike object.
- exception em.FilterError(*args, **kwargs)¶
- exception em.Flow¶
- class em.IconToken(current, config, first)¶
An icon markup:
@|...
- class em.InPlaceToken(current, config, first)¶
An in-place markup:
@$...$...$
- class em.InlineCommentToken(current, config, first)¶
An inline comment markup:
@* ... *
- class em.Interpreter(**kwargs)¶
An interpreter can process chunks of EmPy code.
- addHook(hook, prepend=False)¶
Add a new hook; optionally insert it rather than appending it.
- appendFilter(filter)¶
Attach a single filter to the end of the current filter chain.
- appendFinalizer(finalizer)¶
Register a function to be called at exit.
- appendHook(hook)¶
Append the given hook.
- areHooksEnabled()¶
Return whether or not hooks are presently enabled.
- assign(name, value, locals=None)¶
Do a potentially complex (including tuple unpacking) assignment.
- atExit(finalizer)¶
Register a function to be called at exit.
- atomic(name, value, locals=None)¶
Do an atomic assignment.
- bottom(output)¶
Get the underlying bottom file.
- check()¶
Check the verify this interpreter is still alive.
- clause(catch, locals=None)¶
Given the string representation of an except clause, turn it into a 2-tuple consisting of the class name or tuple of names, and either a variable name or None. If the representation is None, then it’s all exceptions and no name.
- clearFinalizers()¶
Clear all finalizers.
- clearGlobals()¶
Clear out the globals with a brand new dictionary.
- clearHooks()¶
Clear all hooks.
- createDiversion(name)¶
Create a diversion (but do not divert to it) if it does not already exist.
- defaultHandler(type, error, traceback)¶
Report an error.
- defined(name, locals=None)¶
Return a Boolean indicating whether or not the name is defined either in the locals or the globals.
- deregisterCallback()¶
Remove any previously registered custom markup callback with this interpreter.
- dictionary(code, locals=None)¶
Given a string representing a key-value argument list, turn it into a dictionary.
- disableHooks()¶
Disable hooks.
- dispatch(triple=None)¶
Dispatch an exception.
- dropAllDiversions()¶
Drop all existing diversions.
- dropDiversion(name)¶
Eliminate the given diversion.
- ejectCore()¶
Clear the execution core, breaking a potential cyclical link.
- enableHooks()¶
Enable hooks.
- escape(data, more='')¶
Escape a string so that nonprintable or non-ASCII characters are replaced with compatible EmPy expansions. Also treat characters in more as escapes.
- evaluate(expression, locals=None, replace=True)¶
Evaluate an expression. If replace is true, replace newlines in the expression with spaces if that config variable is set; otherwise, don’t do it regardless.
- execute(statements, locals=None)¶
Execute a statement(s).
- exit(exitCode=None)¶
Exit. If exitCode is None, use the exit code from the current error (which may itself be None for no error).
- expand(data, locals=None, name='<expand>', dispatcher=False)¶
Do an explicit expansion on a subordinate stream in a new context. If dispatch is true, dispatch any exception through the interpreter; otherwise just reraise.
- failed()¶
Has this interpreter had an error (which we should not ignore)?
- file(file, locals=None, dispatcher=None)¶
Parse a file according to the current buffering strategy.
- fileChunks(file, bufferSize=None, locals=None, dispatcher=None)¶
Parse the entire contents of a file-like object, in buffered chunks.
- fileFull(file, locals=None, dispatcher=None)¶
Parse the entire contents of a file-like object, in one big chunk.
- fileLines(file, locals=None, dispatcher=None)¶
Parse the entire contents of a file-like object, line by line.
- finalize()¶
Execute any remaining final routines.
- fixGlobals()¶
Reset the globals, stamping in the pseudomodule.
- flattenGlobals(skipKeys=None)¶
Flatten the contents of the pseudo-module into the globals namespace.
- functional(code, tokensLists, locals=None)¶
Handle a functional expression like @f{x} and return the result. code is the Python code to evaluate tokensLists is a list of list of tokens.
- getAllDiversionNames()¶
Get the names of all existing diversions.
- getCallback()¶
Get the custom markup callback registered with this interpreter, or None.
- getContext()¶
Get the top context.
- getCore()¶
Get this interpreter’s core or None.
- getCurrentDiversionName()¶
Get the name of the current diversion.
- getEmojiModule(moduleName)¶
Return an abstracted emoji module by name or return None.
- getEmojiModuleNames()¶
Return the emoji module names in usage in their proper order.
- getExitCode()¶
Get the exit code corresponding for the current error (if any).
- getFilter()¶
Get the top-level filter.
- getFilterCount()¶
Get the number of chained filters; 0 means no active filters.
- getFirstFilter()¶
Get the top-level filter.
- getGlobals()¶
Retrieve the globals.
- getHandler()¶
Get the current handler, or None for the default.
- getHooks()¶
Get the current hooks.
- getLastFilter()¶
Get the last filter in the current chain.
- getPrefix()¶
Get the current prefix.
- go(inputFilename, inputMode, preprocessing=None, postprocessing=None)¶
Execute an interpreter stack at a high level.
- handle(info, fatal=False)¶
Handle an actual error that occurred.
- hasCallback()¶
Is there a custom callback registered?
- hasCore()¶
Does this interpreter have a core inserted?
- hasExtension()¶
Does this interpreter have an extension installed?
- identify()¶
Identify the topmost context with a tuple of the name and counters.
- import_(filename, module, locals=None, dispatcher=None)¶
Import an EmPy module.
- include(fileOrFilename, locals=None, name=None)¶
Do an include pass on a file or filename.
- initializeEmojiModules(moduleNames=None)¶
Determine which emoji module to use. If moduleNames is not specified, use the defaults.
- insertCore(core=None)¶
Insert and attach the execution core.
- install(output)¶
Given the desired output files, install any global apparatus.
- installExtension(extension)¶
Install an extension.
- interact()¶
Perform interaction.
- invoke(_name, **kwargs)¶
Invoke the hook(s) associated with the hook name, should they exist. Stop and return on the first hook which returns a true result.
- invokeCallback(contents)¶
Call the custom markup callback.
- invokeHandler(*args)¶
Manually invoke the error handler with the given exception info 3-tuple or three arguments.
- invokeHook(_name, **kwargs)¶
Invoke the hook(s) associated with the hook name, should they exist. Stop and return on the first hook which returns a true result.
- isExistingDiversionName(name)¶
Does a diversion with this name currently exist?
- literal(text, locals=None)¶
Process a string literal.
- lookup(variable, locals=None)¶
Lookup the value of a variable.
- multi(names, values, locals=None)¶
Do a (potentially recursive) assignment.
- newContext(name='<unnamed>', line=None, column=None, chars=None)¶
Create and return a new context.
- parse(scanner, locals=None)¶
Parse and run as much from this scanner as possible. Return true if the scanner ran out of tokens.
- pause()¶
Pause (at the end of processing).
- playAllDiversions()¶
Play all existing diversions and then drop them.
- playDiversion(name, drop=True)¶
Play the given diversion and then drop it.
- popContext()¶
Pop the top context.
- popGlobals()¶
Pop a globals dictinoary off the history stack and return it.
- prependFilter(filter)¶
Attach a single filter to the end of the current filter chain.
- prependFinalizer(finalizer)¶
Register a function to be called at exit.
- prependHook(hook)¶
Prepend the given hook.
- process(command)¶
Process a command.
- processAll(commands)¶
Process a sequence of commands.
- protect(name, callable, *args, **kwargs)¶
Wrap around an application of a callable in a new context (named name).
- pushContext(context)¶
Push a new context on the stack.
- pushGlobals(globals)¶
Push a globals dictionary onto the history stack.
- quote(data)¶
Quote the given string so that if it were expanded it would evaluate to the original.
- ready()¶
Declare the interpreter ready for normal operations.
- registerCallback(callback)¶
Register a custom markup callback with this interpreter.
- removeHook(hook)¶
Remove a preexisting hook.
- replayAllDiversions()¶
Replay all existing diversions without dropping them.
- replayDiversion(name, drop=False)¶
Replay the diversion without dropping it.
- reraise(*args)¶
Reraise an exception.
- reset(clearStacks=False)¶
Completely reset the interpreter state. If clearStacks is true, wipe the call stacks. If immediately is true, declare the interpreter ready.
- resetCore()¶
Reset the execution core to the default core.
- resetFilter()¶
Reset the filter stream so that it does no filtering.
- restoreContext(oldContext, strict=False)¶
Restore from an old context.
- restoreGlobals(destructive=True)¶
Restore the most recently saved copy of the globals.
- retrieveDiversion(name, *defaults)¶
Retrieve the diversion object associated with the name.
- run(token, locals=None)¶
Run a token, tracking the current context.
- runSeveral(tokens, locals=None)¶
Run a sequence of tokens.
- safe(scanner, final=False, locals=None, dispatcher=None)¶
Do a protected parse. Catch transient parse errors; if final is true, then make a final pass with a terminator, otherwise ignore the transient parse error (more data is pending). Return true if the scanner is exhausted or if an error has occurred.
- saveGlobals(deep=True)¶
Save a copy of the globals off onto the history stack.
- serialize(thing)¶
Output the string version of an object, or a special token if it is None.
- setContext(context)¶
Replace the top context.
- setContextColumn(column)¶
Set the column number of the topmost context.
- setContextData(name=None, line=None, column=None, chars=None)¶
Set any of the name, line, or column of the topmost context.
- setContextLine(line)¶
Set the line number of the topmost context.
- setContextName(name)¶
Set the name of the topmost context.
- setFilter(*filters)¶
Set the filter.
- setFilterChain(filters)¶
Set the filter.
- setGlobals(globals)¶
Set the globals to the specified dictionary.
- setHandler(handler, exitOnError=False)¶
Set the current handler. Additionally, specify whether errors should exit (defaults to false with a custom handler).
- setPrefix(prefix)¶
Set the prefix.
- shutdown()¶
Declare this interpreting session over; close all the stream file objects, and if this is the last interpreter, uninstall the proxy and/or finder. This method is idempotent.
- significate(key, value=None, locals=None)¶
Declare a significator.
- single(source, locals=None)¶
Execute an expression or statement, just as if it were entered into the Python interactive interpreter.
- startDiversion(name)¶
Start diverting to the given diversion name.
- stopDiverting()¶
Stop any diverting.
- string(string, locals=None, dispatcher=None)¶
Parse a string. Cleans up after itself.
- substituteEmoji(text)¶
Substitute an emoji text or return None.
- succeeded()¶
Did the interpreter succeed? That is, is the logged error not an error?
- tokenize(name)¶
Take an lvalue string and return a name or a (possibly recursive) list of names.
- tokens(tokens, locals=None)¶
Do an explicit result on a sequence of tokens. Cleans up after itself.
- top()¶
Get the top stream.
- unfixGlobals()¶
Remove the pseudomodule (if present) from the globals.
- uninstall()¶
Uninstall any global apparatus. The apparatus should be installed.
- uninstallExtension()¶
Uninstall any extension. This should only be done by the interpreter itself at shutdown time.
- updateGlobals(otherGlobals)¶
Merge another mapping object into this interpreter’s globals.
- exception em.InvocationError(*args, **kwargs)¶
- class em.LineCommentToken(current, config, first)¶
A line comment markup:
@# ... NL
- class em.LiteralToken(current, config, first)¶
The abstract base class of the literal tokens. If used as a concrete token class, it will expand to the first character.
- em.Module¶
alias of
EmojiModuleInfo
- class em.NullFile¶
A simple class that supports all the file-like object methods but simply does nothing at all.
- exception em.ParseError(*args, **kwargs)¶
- class em.Plugin¶
A plugin is an object owned by an interpreter that has a back-reference to it.
- attach(interp)¶
Attach this plugin to an interpreter. This needs to be a separate step since some methods require access to the interpreter.
- detach()¶
Detach this plugin from any interpreter. This breaks any cyclical links between the interpreter and core.
- class em.PrefixToken(current, config, first)¶
A prefix markup:
@@
- exception em.ProxyError(*args, **kwargs)¶
- class em.ProxyFile(bottom, wrapper=None)¶
The proxy file object that is intended to take the place of sys.stdout. The proxy can manage a stack of interpreters (and their file object streams) it is writing to, and an underlying bottom file object.
- close()¶
Close the current file. If the current file is the bottom, then flush it (don’t close it) and dispose of it.
- class em.Root¶
The root class of all EmPy class hierarchies. It defines a default __repr__ method which will work appropriately whether or not the subclass defines a __str__ method. Very old versions of Python 2.x won’t print the proper __str__ form, but so be it.
- class em.Scanner(config, context, currents, data='')¶
A scanner holds a buffer for lookahead parsing and has the ability to scan for special symbols and indicators in that buffer.
- accumulate()¶
Update the accumulated context into the actual context.
- acquire()¶
Lock the scanner so it doesn’t destroy data on sync.
- advance(count=1)¶
Advance the pointer count characters.
- all()¶
Yield a sequence of all tokens.
- check(start=0, archetype=None)¶
Scan for the next single or triple quote, optionally with the specified archetype. Return the found quote or None.
- chop(count=None, slop=0)¶
Chop the first count + slop characters off the front, and return the first count, advancing the pointer past them. If count is not specified, then return everything.
- complex(enter, exit, comment='#', start=0, end=None, skip=None)¶
Scan from start for an ending sequence, respecting quotes, entries and exits.
- enclosure(begin='{', end='}')¶
Consume and return the next enclosure (text wrapped in the given delimiters). The delimiters can be repeated.
- feed(data)¶
Feed some more data to the scanner.
- find(sub, start=0, end=None)¶
Find the next occurrence of the substring, or return -1.
- grab(sub, start=0, end=None)¶
Find the next occurrence of the substring and chop the intervening characters, disposing the substring found.
- last(chars, start=0, end=None)¶
Find the first character that is _not_ one of the specified characters.
- nested(enter, exit, start=0, end=None)¶
Scan from start for an ending sequence, respecting entries and exits only.
- next(target, start=0, end=None, mandatory=False)¶
Scan for the next occurrence of one of the characters in the target string; optionally, make the scan mandatory.
- one(firebreaks=None)¶
Parse, scan, and return one token, or None if the scanner is empty. If the firebreaks argument is supplied, chop up text tokens before a character in that string.
- phrase(start=0)¶
Scan from start for a phrase (e.g., ‘word’, ‘f(a, b, c)’, ‘a[i]’, or combinations like ‘x[i](a)’.
- quote(start=0, end=None, mandatory=False)¶
Scan for the end of the next quote.
- read(start=0, count=1)¶
Read count chars starting from start; raise a transient error if there aren’t enough characters remaining.
- rectify()¶
Reset the read head and trim down the buffer.
- release()¶
Unlock the scanner.
- rest()¶
Get the remainder of the buffer.
- set(data)¶
Start the scanner digesting a new batch of data; start the pointer over from scratch.
- simple(start=0)¶
Scan from start for a simple expression, which consists of one more phrases separated by dots. Return a tuple giving the end of the expression and a list of tuple pairs consisting of the simple expression extensions found, if any.
- sync()¶
Sync up the buffer with the read head.
- track()¶
Accumulate the moved pointer into the context.
- trivial(sub, start=0, end=None)¶
Find the first occurrence of the substring where the previous character is _not_ the escape character ``).
- unsync()¶
Undo changes; reset the read head.
- word(start=0, additional='._')¶
Scan from start for a simple word.
- class em.SignificatorToken(current, config, first)¶
A significator markup:
@%... ... NL
,@%!... ... NL
,@%%... ... %% NL
,@%%!... ... %% NL
- class em.SimpleExpressionToken(current, config, first)¶
A simple expression markup:
@x
,@x.y
,@x(y)
,@x[y]
,@f{...}
- class em.SimpleToken(current, config, first)¶
An abstract base class for simple tokens which consist of nothing but the prefix and expand to either the results a function call in the interpreter globals (if args is not specified or is a tuple) or the value of a variable name named function (if args is None).
- class em.Stack(seq=None)¶
A simple stack that is implemented as a sequence.
- clone()¶
Create a duplicate of this stack.
- filter(function)¶
Filter the elements of the stack through the function.
- pop()¶
Pop the top element off the stack and return it.
- purge(function=None)¶
Purge the stack, calling an optional function on each element first from top to bottom.
- push(object)¶
Push an element onto the top of the stack.
- replace(object)¶
Replace the top element of the stack with another one.
- top()¶
Access the top element on the stack.
- exception em.StackUnderflowError(*args, **kwargs)¶
- class em.StatementToken(current, config, first)¶
A statement markup:
@{...}
- class em.Stream(interp, file, diversions)¶
A wrapper around an (output) file object which supports diversions and filtering.
- append(filter)¶
Attach a solitary filter (no sequences allowed here) at the end of the current filter chain.
- count()¶
Count the number of filters.
- create(name)¶
Create a diversion if one does not already exist, but do not divert to it yet. Return the diversion.
- divert(name)¶
Start diverting.
- drop(name)¶
Drop the specified diversion.
- dropAll()¶
Eliminate all existing diversions.
- has(name)¶
Does this stream have a diversion with the given name?
- install(filters=None)¶
Install a list of filters as a chain, replacing the current chain.
- last()¶
Find the last filter in the current filter chain, or None if there are no filters installed.
- names()¶
Return a sorted sequence of diversion names.
- prepend(filter)¶
Attach a solitary filter (no sequences allowed here) at the beginning of the current filter chain.
- retrieve(name, *defaults)¶
Retrieve the given diversion. If an additional argument is provided, return that instead of raising on a nonexistent diversion.
- revert()¶
Reset any current diversions.
- undivert(name, dropAfterwards=False)¶
Undivert a particular diversion.
- undivertAll(dropAfterwards=True)¶
Undivert all pending diversions.
- exception em.StringError(*args, **kwargs)¶
- class em.StringToken(current, config, first)¶
A string token markup:
@'...'
,@'''...'''
,@"..."
,@"""..."""
- class em.SwitchToken(current, config, first)¶
Base class for the enable/disable tokens.
- class em.TextToken(current, data)¶
A chunk of text not containing markups.
- class em.Token(current)¶
An element resulting from parsing.
- exception em.TransientParseError(*args, **kwargs)¶
- class em.UncloseableFile(delegate)¶
A delegating file class that lets through everything except close calls, which it turns into a flush.
- exception em.UnknownEmojiError(*args, **kwargs)¶
- class em.Version¶
An enumerated type representing version detail levels.
- class em.WhitespaceToken(current, config, first)¶
A whitespace markup:
@ WS
- em.details(level, config=None, prelim='Welcome to ', postlim='.\n', file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)¶
Write some details, using the details subsystem if available.
- em.expand(data, _globals=None, _argv=None, _prefix=None, _pseudo=None, _options=None, **kwargs)¶
Do a self-contained expansion of the given source data, creating and shutting down an interpreter dedicated to the task. Expects the same keyword arguments as the Interpreter constructor. Additionally, ‘name’ will identify the expansion filename and ‘locals’, if present, represents the locals dictionary to use. The sys.stdout object is saved off and then replaced before this function returns. Any exception that occurs will be raised to the caller.
- em.extract(dict, key, default)¶
Retrieve the value of the given key in this dictionary, but delete it first. If the key is not present, use the given default.
- em.invoke(args, **kwargs)¶
Run a standalone instance of an EmPy interpreter with the given command line arguments. See the Interpreter constructor for the keyword arguments.
- em.isIdentifier(string, first=True)¶
Is this string a valid identifier? If first is true, make sure the first character is a valid starting identifier character.
- em.toString(value)¶
Convert value to a (Unicode) string.
- em.uliteral(i)¶
Return a wide Unicode string literal.