Module:core.magic
4 Classes
- classIPython.core.magic.MagicsManager(**kwargs:Any)
Bases:
ConfigurableObject that handles all magic-related functionality for IPython.
- __init__(shell=None,config=None,user_magics=None,**traits)
Create a configurable given a config config.
- Parameters:
config (Config) – If this is empty, default values are used. If config is a
Configinstance, it will be used to configure theinstance.parent (Configurable instance,optional) – The parent Configurable instance of this object.
Notes
Subclasses of Configurable must call the
__init__()method ofConfigurablebefore doing anything else and usingsuper():classMyConfigurable(Configurable):def__init__(self,config=None):super(MyConfigurable,self).__init__(config=config)# Then any other code you need to finish initialization.
This ensures that instances will be configured properly.
- auto_magic
Automatically call line magics without requiring explicit % prefix
- auto_status()
Return descriptive string with automagic status.
- lazy_magics
Mapping from magic names to modules to load.
This can be used in IPython/IPykernel configuration to declare lazy magicsthat will only be imported/registered on first use.
For example:
c.MagicsManager.lazy_magics={"my_magic":"slow.to.import","my_other_magic":"also.slow",}
On first invocation of
%my_magic,%%my_magic,%%my_other_magicor%%my_other_magic, the corresponding module will be loaded as an ipythonextensions as if you had previously done%load_extipython.Magics names should be without percent(s) as magics can be both celland line magics.
Lazy loading happen relatively late in execution process, andcomplex extensions that manipulate Python/IPython internal state or global statemight not support lazy loading.
- lsmagic()
Return a dict of currently available magic functions.
The return dict has the keys ‘line’ and ‘cell’, corresponding to thetwo types of magics we support. Each value is a list of names.
- lsmagic_docs(brief=False,missing='')
Return dict of documentation of magic functions.
The return dict has the keys ‘line’ and ‘cell’, corresponding to thetwo types of magics we support. Each value is a dict keyed by magicname whose value is the function docstring. If a docstring isunavailable, the value of
missingis used instead.If brief is True, only the first line of each docstring will be returned.
- register(*magic_objects)
Register one or more instances of Magics.
Take one or more classes or instances of classes that subclass the main
core.Magicclass, and register them with IPython to use the magicfunctions they provide. The registration process will then ensure thatany methods that have decorated to provide line and/or cell magics willbe recognized with the%x/%%xsyntax as a line/cell magicrespectively.If classes are given, they will be instantiated with the defaultconstructor. If your classes need a custom constructor, you shouldinstanitate them first and pass the instance.
The provided arguments can be an arbitrary mix of classes and instances.
- Parameters:
*magic_objects (one ormore classes orinstances)
- register_alias(alias_name,magic_name,magic_kind='line',magic_params=None)
Register an alias to a magic function.
The alias is an instance of
MagicAlias, which holds thename and kind of the magic it should call. Binding is done atcall time, so if the underlying magic function is changed the aliaswill call the new function.
- register_function(func,magic_kind='line',magic_name=None)
Expose a standalone function as magic function for IPython.
This will create an IPython magic (line, cell or both) from astandalone function. The functions should have the followingsignatures:
For line magics:
deff(line)For cell magics:
deff(line,cell)For a function that does both:
deff(line,cell=None)
In the latter case, the function will be called with
cell==Nonewheninvoked as%f, and with cell as a string when invoked as%%f.- Parameters:
func (callable) – Function to be registered as a magic.
magic_kind (str) – Kind of magic, one of ‘line’, ‘cell’ or ‘line_cell’
magic_name (optional str) – If given, the name the magic will have in the IPython namespace. Bydefault, the name of the function itself is used.
- register_lazy(name:str,fully_qualified_name:str)→None
Lazily register a magic via an extension.
- Parameters:
name (str) – Name of the magic you wish to register.
fully_qualified_name – Fully qualified name of the module/submodule that should be loadedas an extensions when the magic is first called.It is assumed that loading this extensions will register the givenmagic.
- classIPython.core.magic.Magics(**kwargs:Any)
Bases:
ConfigurableBase class for implementing magic functions.
Shell functions which can be reached as %function_name. All magicfunctions should accept a string, which they can parse for their ownneeds. This can make some functions easier to type, eg
%cd../vs.%cd("../")Classes providing magic functions need to subclass this class, and theyMUST:
Use the method decorators
@line_magicand@cell_magicto decorateindividual methods as magic functions, ANDUse the class decorator
@magics_classto ensure that the magicmethods are properly registered at the instance level upon instanceinitialization.
See
magic_functionsfor examples of actual implementation classes.- __init__(shell=None,**kwargs)
Create a configurable given a config config.
- Parameters:
config (Config) – If this is empty, default values are used. If config is a
Configinstance, it will be used to configure theinstance.parent (Configurable instance,optional) – The parent Configurable instance of this object.
Notes
Subclasses of Configurable must call the
__init__()method ofConfigurablebefore doing anything else and usingsuper():classMyConfigurable(Configurable):def__init__(self,config=None):super(MyConfigurable,self).__init__(config=config)# Then any other code you need to finish initialization.
This ensures that instances will be configured properly.
- arg_err(func)
Print docstring if incorrect arguments were passed
- default_option(fn,optstr)
Make an entry in the options_table for fn, with value optstr
- format_latex(strng)
Format a string for latex inclusion.
- parse_options(arg_str,opt_str,*long_opts,**kw)
Parse options passed to an argument string.
The interface is similar to that of
getopt.getopt(), but itreturns aStructwith the options as keysand the stripped argument string still as a string.arg_str is quoted as a true sys.argv vector by using shlex.split.This allows us to easily expand variables, glob files, quotearguments, etc.
- Parameters:
arg_str (str) – The arguments to parse.
opt_str (str) – The options specification.
mode (str,default 'string') – If given as ‘list’, the argument string is returned as a list (spliton whitespace) instead of a string.
list_all (bool,default False) – Put all option values in lists. Normally only optionsappearing more than once are put in a list.
posix (bool,default True) – Whether to split the input line in POSIX mode or not, as per theconventions outlined in the
shlexmodule from the standardlibrary.
- classIPython.core.magic.MagicAlias(shell,magic_name,magic_kind,magic_params=None)
Bases:
objectAn alias to another magic function.
An alias is determined by its magic name and magic kind. Lookupis done at call time, so if the underlying magic changes the aliaswill call the new function.
Use the
MagicsManager.register_alias()method or the%alias_magicmagic function to create and register a new alias.- __init__(shell,magic_name,magic_kind,magic_params=None)
8 Functions
- IPython.core.magic.on_off(tag)
Return an ON/OFF string for a 1/0 input. Simple utility function.
- IPython.core.magic.compress_dhist(dh)
Compress a directory history into a new one with at most 20 entries.
Return a new list made from the first and last 10 elements of dhist afterremoval of duplicates.
- IPython.core.magic.needs_local_scope(func)
Decorator to mark magic functions which need to local scope to run.
- IPython.core.magic.magics_class(cls)
Class decorator for all subclasses of the main Magics class.
Any class that subclasses Magicsmust also apply this decorator, toensure that all the methods that have been decorated as line/cell magicsget correctly registered in the class instance. This is necessary becausewhen method decorators run, the class does not exist yet, so theytemporarily store their information into a module global. Application ofthis class decorator copies that global data to the class instance andclears the global.
Obviously, this mechanism is not thread-safe, which means that thecreation of subclasses of Magic should only be done in a single-threadcontext. Instantiation of the classes has no restrictions. Given thatthese classes are typically created at IPython startup time and before userapplication code becomes active, in practice this should not pose anyproblems.
- IPython.core.magic.record_magic(dct,magic_kind,magic_name,func)
Utility function to store a function as a magic of a specific kind.
- IPython.core.magic.validate_type(magic_kind)
Ensure that the given magic_kind is valid.
Check that the given magic_kind is one of the accepted spec types (storedin the global
magic_spec), raise ValueError otherwise.
- IPython.core.magic.no_var_expand(magic_func)
Mark a magic function as not needing variable expansion
By default, IPython interprets
{a}or$ain the line passed to magicsas variables that should be interpolated from the interactive namespacebefore passing the line to the magic function.This is not always desirable, e.g. when the magic executes Python code(%timeit, %time, etc.).Decorate magics with@no_var_expandto opt-out of variable expansion.Added in version 7.3.
- IPython.core.magic.output_can_be_silenced(magic_func)
Mark a magic function so its output may be silenced.
The output is silenced if the Python code used as a parameter ofthe magic ends in a semicolon, not counting a Python comment that canfollow it.