symboldict package

Module contents

symboldict module

class symboldict.BaseSymbolDict(*args, **kwargs)

Bases: builtins.dict

symboldict.LaxSymbolDict(*args, **kwd)
class symboldict.Rule

Bases: enum.Enum

Enumerated rules for SymbolControl.getvalue().

The available values are

DONT_LOAD
TRY_LOAD_ONCE
TRY_LOAD_EACH
FORCE_RELOAD
class symboldict.Symbol(*parts)

Bases: builtins.object

Symbol(*parts) -> new Symbol instance

Parameters:parts (convertibles to str) – A sequence of str or objects convertible to str. These strings are joined by '.' to create the instance’s path.

Example

>>> Symbol('spam.ham', 'eggs')
Symbol('spam.ham.eggs')
>>> Symbol()
Symbol('')
>>> Symbol(None, 12)
Symbol('None.12')

This is the type of objects used as values in SymbolDict instances. Their role is mainly to wrap a dot-separated path to a python object, which may exist or not, with a convenient interface.

Example

>>> Symbol('os.path.isfile')
>>> Symbol('telnetlib.Telnet')
>>> Symbol('complex.conjugate')

Defining an instance does not trigger an attempt to retrieve the indicated python object by importing modules or accessing attributes. This is the role of the SymbolControl.getvalue() or SymbolDict.__getattr__() methods.

__call__()

Calling a Symbol instance wraps it into a SymbolControl object.

Returns:a lightweight object wrapping the Symbol.
Return type:SymbolControl

This allows to bypass the overloading of the dot operator to access some methods.

Example

>>> s = Symbol('os.path.isfile')
>>> s().getvalue()
<function isfile at ...>
__eq__(other)

Equality relation with another instance.

A Symbol x is equal to a python object y if they have the same type and the same path.

Example

>>> x = Symbol('spam.ham')
>>> y = Symbol('spam.ham')
>>> x == y
True
>>> x == 'spam.ham'
False

The relations !=, <, >, <=, >= are defined as well.

__getattribute__(attr)

Overridden attribute access creates a new Symbol.

Parameters:attr (str) – new path element

Example

>>> Symbol('spam').eggs
Symbol('spam.eggs')
__hash__()

Computes a hash value for the Symbol instance.

Returns:the instance’s hash value
Return type:int

Symbol instances are hashable objects which can be used as dictionary keys or as set elements.

Example

>>> S = set([Symbol('spam.ham'), Symbol('eggs')])
>>> Symbol('eggs') in S
True
__setattr__(attr, value)

Attribute setting is disabled for Symbol instances.

Raises:TypeError – this exception is always raised.

Example

>>> s = Symbol('spam')
>>> s.ham = 'eggs'
Traceback ...
TypeError: Attribute setting is disabled for Symbol instances
__str__()

Converting a Symbol to str returns the wrapped path.

Returns:the string stored in the Symbol instance.
Return type:str

Example

>>> s = Symbol('spam.ham').eggs
>>> s
Symbol('spam.ham.eggs')
>>> str(s)
'spam.ham.eggs'
class symboldict.SymbolControl(symb)

Bases: builtins.object

SymbolControl(symb) -> new SymbolControl instance

Parameters:symb (Symbol) – a symbol referenced by the SymbolControl object

This is a class of lightweight wrappers around Symbol instances used to bypass the overriding of the dot operator in this class. SymbolControl objects are returned by the Symbol.__call__() method. Their main purpose is to hold methods to manipulate Symbols.

Example

>>> s = Symbol('os.path.isfile')
>>> s()
<symboldict.SymbolControl object ...>
>>> s().hasvalue()
True
>>> s().path()
'os.path.isfile'
>>> s().getvalue()
<function isfile ...>
getvalue(rule=<Rule.TRY_LOAD_ONCE: 1>)

Attempts to return the python object referenced symbolically by this instance.

Parameters:

rule (Rule) – a rule specifying how to obtain the object’s value. It defaults to Rule.TRY_LOAD_ONCE.

Returns:

a python object referenced by this instance, if such a value can be found.

Return type:

any

Raises:

Exception

met while trying to obtain the value when it does not exist.

This method tries to obtain a value by importing modules and taking attributes according to the dotted path of the contained Symbol instance. In this path, the word before the first dot can be the name of an importable module or that of a builtin python object in the __builtins__ dictionnary.

If the object can not be found, an exception is raised.

Example

>>> a = Symbol('wave.Error')
>>> a().getvalue()
<class 'wave.Error'>

The rule parameter can be used to specify the policy with respect to value search. The possible values are

  • Rule.TRY_LOAD_ONCE (default rule) The value

    is searched once and stored in the Symbol instance. Subsequent calls to getvalue() return the same value without trying to reload the symbol. If the first search fails, subsequent calls will fail without attempting to search the value. This rule handles most lazy import cases because symbol values in imported modules usually don’t vary. For example there is no need to search the symbol Symbol('telnetlib.Telnet') more than once. This is a per-instance policy, which means that a different instance with the same path will trigger a second search.

  • Rule.DONT_LOAD With this rule, there is no attempt to get

    the symbol’s value through imports or attribute accesses. It means that the call will succeed only if a value was previously found by a call to getvalue() or hasvalue() with a different rule.

  • Rule.FORCE_RELOAD With this rule, an attempt is made to load

    the symbol through imports and attribute access. It can be used to handle cases where a variable changes in an imported module. There is no attempt to reload imported modules.

  • Rule.TRY_LOAD_EACH With this rule, an attempt is made to load

    the symbol’s value only if the previous attempts failed to obtain a value.

hasvalue(rule=<Rule.TRY_LOAD_ONCE: 1>)

Returns a boolean indicating if a value is available for the python object referenced symbolically by this instance.

Parameters:rule (Rule) – a rule specifying how to obtain the object’s value. It defaults to Rule.TRY_LOAD_ONCE.
Returns:a boolean indicating if a value is available for this instance.
Return type:bool

This method returns True if the corresponding call to getvalue() would succeed, and returns False if the call to getvalue() would fail. In any case, it does not raise an exception.

The rule argument has the same meaning as in Symbol.getvalue().

Example

>>> a = Symbol('wave.Error')
>>> a().hasvalue()
True
>>> b = Symbol('spam.ham')
>>> b().hasvalue()
False
path()

Returns the path of the referenced Symbol instance.

Example

>>> s = Symbol('socket.socket')
>>> s().path()
'socket.socket'
symbol()

Returns the referenced Symbol instance.

Example

>>> s = Symbol('socket.socket')
>>> s().symbol() is s
True
class symboldict.SymbolDict(*args, **kwargs)

Bases: symboldict.BaseSymbolDict

SymbolDict() -> new empty SymbolDict SymbolDict(mapping) -> new SymbolDict initiliazed from a mapping object’s

(key, value) pairs. The values are converted to Symbol instances.
SymbolDict(iterable) -> new SymbolDict initialized as if via::

d = SymbolDict() for k, v in iterable:

d[k] = Symbol(v)
SymbolDict(**kwargs) -> new SymbolDict initialized with the name=value pairs
in the keyword argument list. For example: SymbolDict(one=’spam.eggs’, two=’os’). The values are converted to Symbol instances.

SymbolDict is a subclass of dict, which means that the usual dict methods (clear, copy, get, items, keys, pop, popitem, setdefault, update, values) apply. The main differences are

Example

>>> from symboldict import symbol, SymbolDict
>>> sy = SymbolDict(
...     isfile=symbol.os.path.isfile,
...     Telnet=symbol.telnetlib.Telnet,
...     conju=symbol.complex.conjugate,
...     eggs=symbol.spam.eggs,
... )
>>> sy['isfile']
Symbol('os.path.isfile')
>>> sy['eggs']
Symbol('spam.eggs')
>>> sy['Parser'] = Symbol('argparse.ArgumentParser')
>>> 'Telnet' in sy
True
>>> sy.isfile
<function isfile ...'>
>>> sy.Telnet
<class 'telnetlib.Telnet ...'>
>>> sy.conju
<method 'conjugate' of 'complex' objects>
>>> sy.eggs
Traceback ...
ImportError: No module named spam
>>> sy.hasvalue('isfile')
True
>>> sy.getvalue('Parser')
<class 'argparse.ArgumentParser'>
__getattr__(attr)

Identical to self().getvalue(attr) but raises AttributeError if attr is not a dictionary key.

Example

>>> sy = SymbolDict(isfile='os.path.isfile')
>>> sy.isfile
<function isfile at ...>
__setitem__(k, v)

Like dict.__setitem__() but converts value to Symbol

getvalue(key, rule=<Rule.TRY_LOAD_ONCE: 1>)

Attempts to return the python object referenced symbolically by the Symbol under the given key.

Parameters:
  • key (hashable) – one of the dictionary keys of the wrapped SymbolDict instance.
  • rule (Rule) – a rule specifying how to obtain the object’s value. It defaults to Rule.TRY_LOAD_ONCE.
Returns:

a python object referenced by this instance, if such a value can be found.

Return type:

any

Raises:

Exception

met while trying to obtain the value when it does not exist. Also raises KeyError if the key is missing in this SymbolDict.

This method tries to obtain a value by importing modules and taking attributes according to the dotted path of the Symbol instance self[key]. In this path, the word before the first dot can be the name of an importable module or that of a builtin python object in the __builtins__ dictionnary.

If the object can not be found, an exception is raised.

The rule argument has the same meaning as in the SymbolControl.getvalue() method. See this method’s documentation for details.

Example

>>> sy = SymbolDict(err=Symbol('wave.Error'))
>>> sy.getvalue('err')
<class 'wave.Error'>
hasvalue(key, rule=<Rule.TRY_LOAD_ONCE: 1>)

Returns a boolean indicating if a value is available for the python object referenced symbolically by the symbol under this key.

Parameters:
  • key (hashable) – one of the dictionary keys of this SymbolDict
  • rule (Rule) – a rule specifying how to obtain the object’s value. It defaults to Rule.TRY_LOAD_ONCE.
Returns:

a boolean indicating if a value is available for this key.

Return type:

bool

Raises:

KeyError – if the key is missing.

If the key is missing in this SymbolDict, the method raises a KeyError exception, otherwise, it returns True if the corresponding call to getvalue() would succeed, and returns False if the call to getvalue() would fail.

The rule argument has the same meaning as in Symbol.getvalue(). See this method’s documentation for details.

Example

>>> sy = SymbolDict(err='wave.Error', ham='spam.ham')
>>> sy.hasvalue('err')
True
>>> sy.hasvalue('ham')
False
>>> sy.hasvalue('eggs')
Traceback ...
KeyError
setdefault(k, v)

Like dict.setdefault() but converts value to Symbol

strict
symboldict = functools.partial(<function update_wrapper at 0x7fd155a4c488>, updated=('__dict__',), wrapped=<function deprecated.<locals>.new_func at 0x7fd1524da510>, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'))
update([E, ]**F) → None. Update SymbolDict ``sy`` from dict/iterable E and F.
  • If E is present and has a .keys() method, then does: for k in E: sy[k] = Symbol(E[k])
  • If E is present and lacks a .keys() method, then does: for k, v in E: sy[k] = Symbol(v)
  • In either case, this is followed by: for k in F: sy[k] = Symbol(F[k])

The only difference with dict.update() is that values are converted to Symbol instances.

exception symboldict.VoidValueError

Bases: builtins.ValueError

symboldict.deprecated(func)

This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.

ref:
https://wiki.python.org/moin/PythonDecoratorLibrary#Generating_Deprecation_Warnings

Table Of Contents

Previous topic

Welcome to symboldict’s documentation!

This Page