index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
11,754 | hstspreload | _iter_entries | null | def _iter_entries(data: bytes) -> typing.Iterable[typing.Tuple[int, int, bytes]]:
while data:
flags = data[0]
size = data[1]
label = bytes(data[2 : 2 + size])
yield (flags & _IS_LEAF, flags & _INCLUDE_SUBDOMAINS, label)
data = data[2 + size :]
| (data: bytes) -> Iterable[Tuple[int, int, bytes]] |
11,756 | importlib.resources | open_binary | Return a file-like object opened for binary reading of the resource. | def open_binary(package: Package, resource: Resource) -> BinaryIO:
"""Return a file-like object opened for binary reading of the resource."""
resource = _common.normalize_path(resource)
package = _common.get_package(package)
reader = _common.get_resource_reader(package)
if reader is not None:
return reader.open_resource(resource)
spec = cast(ModuleSpec, package.__spec__)
# Using pathlib doesn't work well here due to the lack of 'strict'
# argument for pathlib.Path.resolve() prior to Python 3.6.
if spec.submodule_search_locations is not None:
paths = spec.submodule_search_locations
elif spec.origin is not None:
paths = [os.path.dirname(os.path.abspath(spec.origin))]
for package_path in paths:
full_path = os.path.join(package_path, resource)
try:
return open(full_path, mode='rb')
except OSError:
# Just assume the loader is a resource loader; all the relevant
# importlib.machinery loaders are and an AttributeError for
# get_data() will make it clear what is needed from the loader.
loader = cast(ResourceLoader, spec.loader)
data = None
if hasattr(spec.loader, 'get_data'):
with suppress(OSError):
data = loader.get_data(full_path)
if data is not None:
return BytesIO(data)
raise FileNotFoundError(f'{resource!r} resource not found in {spec.name!r}')
| (package: Union[str, module], resource: Union[str, os.PathLike]) -> <class 'BinaryIO'> |
11,757 | hstspreload | open_pkg_binary | null | def open_pkg_binary(path: str) -> typing.BinaryIO:
return open_binary("hstspreload", path)
| (path: str) -> <class 'BinaryIO'> |
11,760 | mozdebug.mozdebug | DebuggerInfo | DebuggerInfo(path, interactive, args, requiresEscapedArgs) | from mozdebug.mozdebug import DebuggerInfo
| (path, interactive, args, requiresEscapedArgs) |
11,762 | namedtuple_DebuggerInfo | __new__ | Create new instance of DebuggerInfo(path, interactive, args, requiresEscapedArgs) | from builtins import function
| (_cls, path, interactive, args, requiresEscapedArgs) |
11,765 | collections | _replace | Return a new DebuggerInfo object replacing specified fields with new values | def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
# Validate the field names. At the user's option, either generate an error
# message or automatically replace the field name with a valid name.
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = _sys.intern(str(typename))
if rename:
seen = set()
for index, name in enumerate(field_names):
if (not name.isidentifier()
or _iskeyword(name)
or name.startswith('_')
or name in seen):
field_names[index] = f'_{index}'
seen.add(name)
for name in [typename] + field_names:
if type(name) is not str:
raise TypeError('Type names and field names must be strings')
if not name.isidentifier():
raise ValueError('Type names and field names must be valid '
f'identifiers: {name!r}')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
f'keyword: {name!r}')
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
f'{name!r}')
if name in seen:
raise ValueError(f'Encountered duplicate field name: {name!r}')
seen.add(name)
field_defaults = {}
if defaults is not None:
defaults = tuple(defaults)
if len(defaults) > len(field_names):
raise TypeError('Got more default values than field names')
field_defaults = dict(reversed(list(zip(reversed(field_names),
reversed(defaults)))))
# Variables used in the methods and docstrings
field_names = tuple(map(_sys.intern, field_names))
num_fields = len(field_names)
arg_list = ', '.join(field_names)
if num_fields == 1:
arg_list += ','
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
tuple_new = tuple.__new__
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
# Create all the named tuple methods to be added to the class namespace
namespace = {
'_tuple_new': tuple_new,
'__builtins__': {},
'__name__': f'namedtuple_{typename}',
}
code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
__new__ = eval(code, namespace)
__new__.__name__ = '__new__'
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
@classmethod
def _make(cls, iterable):
result = tuple_new(cls, iterable)
if _len(result) != num_fields:
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
return result
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
'or iterable')
def _replace(self, /, **kwds):
result = self._make(_map(kwds.pop, field_names, self))
if kwds:
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
return result
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
'fields with new values')
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self
def _asdict(self):
'Return a new dict which maps field names to their values.'
return _dict(_zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return _tuple(self)
# Modify function metadata to help with introspection and debugging
for method in (
__new__,
_make.__func__,
_replace,
__repr__,
_asdict,
__getnewargs__,
):
method.__qualname__ = f'{typename}.{method.__name__}'
# Build-up the class namespace dictionary
# and use type() to build the result class
class_namespace = {
'__doc__': f'{typename}({arg_list})',
'__slots__': (),
'_fields': field_names,
'_field_defaults': field_defaults,
'__new__': __new__,
'_make': _make,
'_replace': _replace,
'__repr__': __repr__,
'_asdict': _asdict,
'__getnewargs__': __getnewargs__,
'__match_args__': field_names,
}
for index, name in enumerate(field_names):
doc = _sys.intern(f'Alias for field number {index}')
class_namespace[name] = _tuplegetter(index, doc)
result = type(typename, (tuple,), class_namespace)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython), or where the user has
# specified a particular module.
if module is None:
try:
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
if module is not None:
result.__module__ = module
return result
| (self, /, **kwds) |
11,766 | mozdebug.mozdebug | DebuggerSearch | null | class DebuggerSearch:
OnlyFirst = 1
KeepLooking = 2
| () |
11,767 | mozdebug.mozdebug | get_debugger_info |
Get the information about the requested debugger.
Returns a dictionary containing the ``path`` of the debugger executable,
if it will run in ``interactive`` mode, its arguments and whether it needs
to escape arguments it passes to the debugged program (``requiresEscapedArgs``).
If the debugger cannot be found in the system, returns ``None``.
:param debugger: The name of the debugger.
:param debuggerArgs: If specified, it's the arguments to pass to the debugger,
as a string. Any debugger-specific separator arguments are appended after
these arguments.
:param debuggerInteractive: If specified, forces the debugger to be interactive.
| def get_debugger_info(debugger, debuggerArgs=None, debuggerInteractive=False):
"""
Get the information about the requested debugger.
Returns a dictionary containing the ``path`` of the debugger executable,
if it will run in ``interactive`` mode, its arguments and whether it needs
to escape arguments it passes to the debugged program (``requiresEscapedArgs``).
If the debugger cannot be found in the system, returns ``None``.
:param debugger: The name of the debugger.
:param debuggerArgs: If specified, it's the arguments to pass to the debugger,
as a string. Any debugger-specific separator arguments are appended after
these arguments.
:param debuggerInteractive: If specified, forces the debugger to be interactive.
"""
debuggerPath = None
if debugger:
# Append '.exe' to the debugger on Windows if it's not present,
# so things like '--debugger=devenv' work.
if os.name == "nt" and not debugger.lower().endswith(".exe"):
debugger += ".exe"
debuggerPath = get_debugger_path(debugger)
if not debuggerPath:
# windbg is not installed with the standard set of tools, and it's
# entirely possible that the user hasn't added the install location to
# PATH, so we have to be a little more clever than normal to locate it.
# Just try to look for it in the standard installed location(s).
if debugger == "windbg.exe":
for candidate in _windbg_installation_paths():
if os.path.exists(candidate):
debuggerPath = candidate
break
else:
if os.path.exists(debugger):
debuggerPath = debugger
if not debuggerPath:
print("Error: Could not find debugger %s." % debugger)
print("Is it installed? Is it in your PATH?")
return None
debuggerName = os.path.basename(debuggerPath).lower()
def get_debugger_info(type, default):
if debuggerName in _DEBUGGER_INFO and type in _DEBUGGER_INFO[debuggerName]:
return _DEBUGGER_INFO[debuggerName][type]
return default
# Define a namedtuple to access the debugger information from the outside world.
debugger_arguments = []
if debuggerArgs:
# Append the provided debugger arguments at the end of the arguments list.
debugger_arguments += debuggerArgs.split()
debugger_arguments += get_debugger_info("args", [])
# Override the default debugger interactive mode if needed.
debugger_interactive = get_debugger_info("interactive", False)
if debuggerInteractive:
debugger_interactive = debuggerInteractive
d = DebuggerInfo(
debuggerPath,
debugger_interactive,
debugger_arguments,
get_debugger_info("requiresEscapedArgs", False),
)
return d
| (debugger, debuggerArgs=None, debuggerInteractive=False) |
11,768 | mozdebug.mozdebug | get_default_debugger_name |
Get the debugger name for the default debugger on current platform.
:param search: If specified, stops looking for the debugger if the
default one is not found (``DebuggerSearch.OnlyFirst``) or keeps
looking for other compatible debuggers (``DebuggerSearch.KeepLooking``).
| def get_default_debugger_name(search=DebuggerSearch.OnlyFirst):
"""
Get the debugger name for the default debugger on current platform.
:param search: If specified, stops looking for the debugger if the
default one is not found (``DebuggerSearch.OnlyFirst``) or keeps
looking for other compatible debuggers (``DebuggerSearch.KeepLooking``).
"""
mozinfo.find_and_update_from_json()
os = mozinfo.info["os"]
# Find out which debuggers are preferred for use on this platform.
debuggerPriorities = _DEBUGGER_PRIORITIES[
os if os in _DEBUGGER_PRIORITIES else "unknown"
]
# Finally get the debugger information.
for debuggerName in debuggerPriorities:
debuggerPath = get_debugger_path(debuggerName)
if debuggerPath:
return debuggerName
elif not search == DebuggerSearch.KeepLooking:
return None
return None
| (search=1) |
11,769 | mozdebug.mozdebug | get_default_valgrind_args | null | def get_default_valgrind_args():
return [
"--fair-sched=yes",
"--smc-check=all-non-file",
"--vex-iropt-register-updates=allregs-at-mem-access",
"--trace-children=yes",
"--child-silent-after-fork=yes",
(
"--trace-children-skip="
+ "/usr/bin/hg,/bin/rm,*/bin/certutil,*/bin/pk12util,"
+ "*/bin/ssltunnel,*/bin/uname,*/bin/which,*/bin/ps,"
+ "*/bin/grep,*/bin/java,*/bin/lsb_release"
),
] + get_default_valgrind_tool_specific_args()
| () |
11,771 | asn1crypto | load_order |
Returns a list of the module and sub-module names for asn1crypto in
dependency load order, for the sake of live reloading code
:return:
A list of unicode strings of module names, as they would appear in
sys.modules, ordered by which module should be reloaded first
| def load_order():
"""
Returns a list of the module and sub-module names for asn1crypto in
dependency load order, for the sake of live reloading code
:return:
A list of unicode strings of module names, as they would appear in
sys.modules, ordered by which module should be reloaded first
"""
return [
'asn1crypto._errors',
'asn1crypto._int',
'asn1crypto._ordereddict',
'asn1crypto._teletex_codec',
'asn1crypto._types',
'asn1crypto._inet',
'asn1crypto._iri',
'asn1crypto.version',
'asn1crypto.pem',
'asn1crypto.util',
'asn1crypto.parser',
'asn1crypto.core',
'asn1crypto.algos',
'asn1crypto.keys',
'asn1crypto.x509',
'asn1crypto.crl',
'asn1crypto.csr',
'asn1crypto.ocsp',
'asn1crypto.cms',
'asn1crypto.pdf',
'asn1crypto.pkcs12',
'asn1crypto.tsp',
'asn1crypto',
]
| () |
11,773 | kpush | KPush | null | class KPush(object):
domain = None
appkey = None
appsecret = None
def __init__(self, domain, appkey, appsecret):
self.domain = domain
self.appkey = appkey
self.appsecret = appsecret
def push(self, title, content, query, silent=False):
"""
推送
:param title: 标题
:param content: 内容
:param query: 字典格式
all: True 代表所有人,其他字段即无效
alias: 为None代表不过滤
tags_or: [
["x", "y", "z"],
["a", "b", "c"],
]
:param silent:
:return:
"""
url = 'http://%s/api/push' % self.domain
body = self.pack_data(dict(
title=safe_str(title),
content=safe_str(content),
query=query,
silent=silent
))
rsp = requests.post(url, body)
if not rsp.ok:
return -1, 'status code: %s' % rsp.status_code
return rsp.json()['ret'], rsp.json().get('error')
def pack_data(self, json_data):
"""
:param json_data:
:return:
"""
if json_data is None:
return ""
data = json.dumps(json_data)
sign = hashlib.md5('|'.join([self.appsecret, self.appkey, data])).hexdigest()
return json.dumps(dict(
appkey=self.appkey,
data=data,
sign=sign,
))
| (domain, appkey, appsecret) |
11,774 | kpush | __init__ | null | def __init__(self, domain, appkey, appsecret):
self.domain = domain
self.appkey = appkey
self.appsecret = appsecret
| (self, domain, appkey, appsecret) |
11,775 | kpush | pack_data |
:param json_data:
:return:
| def pack_data(self, json_data):
"""
:param json_data:
:return:
"""
if json_data is None:
return ""
data = json.dumps(json_data)
sign = hashlib.md5('|'.join([self.appsecret, self.appkey, data])).hexdigest()
return json.dumps(dict(
appkey=self.appkey,
data=data,
sign=sign,
))
| (self, json_data) |
11,776 | kpush | push |
推送
:param title: 标题
:param content: 内容
:param query: 字典格式
all: True 代表所有人,其他字段即无效
alias: 为None代表不过滤
tags_or: [
["x", "y", "z"],
["a", "b", "c"],
]
:param silent:
:return:
| def push(self, title, content, query, silent=False):
"""
推送
:param title: 标题
:param content: 内容
:param query: 字典格式
all: True 代表所有人,其他字段即无效
alias: 为None代表不过滤
tags_or: [
["x", "y", "z"],
["a", "b", "c"],
]
:param silent:
:return:
"""
url = 'http://%s/api/push' % self.domain
body = self.pack_data(dict(
title=safe_str(title),
content=safe_str(content),
query=query,
silent=silent
))
rsp = requests.post(url, body)
if not rsp.ok:
return -1, 'status code: %s' % rsp.status_code
return rsp.json()['ret'], rsp.json().get('error')
| (self, title, content, query, silent=False) |
11,780 | kpush | safe_str | null | def safe_str(src):
if isinstance(src, unicode):
return src.encode('utf8')
return str(src)
| (src) |
11,784 | htmldate.core | find_date |
Extract dates from HTML documents using markup analysis and text patterns
:param htmlobject:
Two possibilities: 1. HTML document (e.g. body of HTTP request or .html-file) in text string
form or LXML parsed tree or 2. URL string (gets detected automatically)
:type htmlobject: string or lxml tree
:param extensive_search:
Activate pattern-based opportunistic text search
:type extensive_search: boolean
:param original_date:
Look for original date (e.g. publication date) instead of most recent
one (e.g. last modified, updated time)
:type original_date: boolean
:param outputformat:
Provide a valid datetime format for the returned string
(see datetime.strftime())
:type outputformat: string
:param url:
Provide an URL manually for pattern-searching in URL
(in some cases much faster)
:type url: string
:param verbose:
Set verbosity level for debugging
:type verbose: boolean
:param min_date:
Set the earliest acceptable date manually (ISO 8601 YMD format)
:type min_date: datetime, string
:param max_date:
Set the latest acceptable date manually (ISO 8601 YMD format)
:type max_date: datetime, string
:param deferred_url_extractor:
Use url extractor as backup only to prioritize full expressions,
e.g. of the type `%Y-%m-%d %H:%M:%S`
:type deferred_url_extractor: boolean
:return: Returns a valid date expression as a string, or None
| def find_date(
htmlobject: Union[bytes, str, HtmlElement],
extensive_search: bool = True,
original_date: bool = False,
outputformat: str = "%Y-%m-%d",
url: Optional[str] = None,
verbose: bool = False,
min_date: Optional[Union[datetime, str]] = None,
max_date: Optional[Union[datetime, str]] = None,
deferred_url_extractor: bool = False,
) -> Optional[str]:
"""
Extract dates from HTML documents using markup analysis and text patterns
:param htmlobject:
Two possibilities: 1. HTML document (e.g. body of HTTP request or .html-file) in text string
form or LXML parsed tree or 2. URL string (gets detected automatically)
:type htmlobject: string or lxml tree
:param extensive_search:
Activate pattern-based opportunistic text search
:type extensive_search: boolean
:param original_date:
Look for original date (e.g. publication date) instead of most recent
one (e.g. last modified, updated time)
:type original_date: boolean
:param outputformat:
Provide a valid datetime format for the returned string
(see datetime.strftime())
:type outputformat: string
:param url:
Provide an URL manually for pattern-searching in URL
(in some cases much faster)
:type url: string
:param verbose:
Set verbosity level for debugging
:type verbose: boolean
:param min_date:
Set the earliest acceptable date manually (ISO 8601 YMD format)
:type min_date: datetime, string
:param max_date:
Set the latest acceptable date manually (ISO 8601 YMD format)
:type max_date: datetime, string
:param deferred_url_extractor:
Use url extractor as backup only to prioritize full expressions,
e.g. of the type `%Y-%m-%d %H:%M:%S`
:type deferred_url_extractor: boolean
:return: Returns a valid date expression as a string, or None
"""
# init
if verbose:
logging.basicConfig(level=logging.DEBUG)
tree = load_html(htmlobject)
# safeguards
if tree is None:
return None
if outputformat != "%Y-%m-%d" and not is_valid_format(outputformat):
return None
# define options and time boundaries
options = Extractor(
extensive_search,
get_max_date(max_date),
get_min_date(min_date),
original_date,
outputformat,
)
# unclear what this line is for and it impedes type checking:
# find_date.extensive_search = extensive_search
# URL
url_result = None
if url is None:
# probe for canonical links
urlelem = tree.find('.//link[@rel="canonical"]')
if urlelem is not None:
url = urlelem.get("href")
# direct processing of URL info
url_result = extract_url_date(url, options)
if url_result is not None and not deferred_url_extractor:
return url_result
# first try header
# then try to use JSON data
result = examine_header(tree, options) or json_search(tree, options)
if result is not None:
return result
# deferred processing of URL info (may be moved even further down if necessary)
if deferred_url_extractor and url_result is not None:
return url_result
# try abbr elements
abbr_result = examine_abbr_elements(
tree,
options,
)
if abbr_result is not None:
return abbr_result
# first, prune tree
try:
search_tree, discarded = discard_unwanted(
clean_html(deepcopy(tree), CLEANING_LIST)
)
# rare LXML error: no NULL bytes or control characters
except ValueError: # pragma: no cover
search_tree = tree
LOGGER.error("lxml cleaner error")
# define expressions + text_content
if extensive_search:
date_expr = SLOW_PREPEND + DATE_EXPRESSIONS
else:
date_expr = FAST_PREPEND + DATE_EXPRESSIONS
# then look for expressions
# and try time elements
result = (
examine_date_elements(
search_tree,
date_expr,
options,
)
or examine_date_elements(
search_tree,
".//title|.//h1",
options,
)
or examine_time_elements(search_tree, options)
)
if result is not None:
return result
# TODO: decide on this
# search in discarded parts (e.g. archive.org-banner)
# for subtree in discarded:
# dateresult = examine_date_elements(subtree, DATE_EXPRESSIONS, options)
# if dateresult is not None:
# return dateresult
# robust conversion to string
try:
htmlstring = tostring(search_tree, pretty_print=False, encoding="unicode")
except UnicodeDecodeError:
htmlstring = tostring(search_tree, pretty_print=False).decode("utf-8", "ignore")
# date regex timestamp rescue
# try image elements
# precise patterns and idiosyncrasies
result = (
pattern_search(htmlstring, TIMESTAMP_PATTERN, options)
or img_search(search_tree, options)
or idiosyncrasies_search(htmlstring, options)
)
if result is not None:
return result
# last resort
if extensive_search:
LOGGER.debug("extensive search started")
# TODO: further tests & decide according to original_date
reference = 0
for segment in FREE_TEXT_EXPRESSIONS(search_tree):
segment = segment.strip()
if not MIN_SEGMENT_LEN < len(segment) < MAX_SEGMENT_LEN:
continue
reference = compare_reference(reference, segment, options)
converted = check_extracted_reference(reference, options)
# return or search page HTML
return converted or search_page(htmlstring, options)
return None
| (htmlobject: Union[bytes, str, lxml.html.HtmlElement], extensive_search: bool = True, original_date: bool = False, outputformat: str = '%Y-%m-%d', url: Optional[str] = None, verbose: bool = False, min_date: Union[datetime.datetime, str, NoneType] = None, max_date: Union[datetime.datetime, str, NoneType] = None, deferred_url_extractor: bool = False) -> Optional[str] |
11,789 | ipyleaflet.leaflet | AntPath | AntPath class, with VectorLayer as parent class.
AntPath layer.
Attributes
----------
locations: list, default []
Locations through which the ant-path is going.
use: string, default 'polyline'
Type of shape to use for the ant-path. Possible values are 'polyline', 'polygon',
'rectangle' and 'circle'.
delay: int, default 400
Add a delay to the animation flux.
weight: int, default 5
Weight of the ant-path.
dash_array: list, default [10, 20]
The sizes of the animated dashes.
color: CSS color, default '#0000FF'
The color of the primary dashes.
pulse_color: CSS color, default '#FFFFFF'
The color of the secondary dashes.
paused: boolean, default False
Whether the animation is running or not.
reverse: boolean, default False
Whether the animation is going backwards or not.
hardware_accelerated: boolean, default False
Whether the ant-path uses hardware acceleration.
radius: int, default 10
Radius of the circle, if use is set to ‘circle’
| class AntPath(VectorLayer):
"""AntPath class, with VectorLayer as parent class.
AntPath layer.
Attributes
----------
locations: list, default []
Locations through which the ant-path is going.
use: string, default 'polyline'
Type of shape to use for the ant-path. Possible values are 'polyline', 'polygon',
'rectangle' and 'circle'.
delay: int, default 400
Add a delay to the animation flux.
weight: int, default 5
Weight of the ant-path.
dash_array: list, default [10, 20]
The sizes of the animated dashes.
color: CSS color, default '#0000FF'
The color of the primary dashes.
pulse_color: CSS color, default '#FFFFFF'
The color of the secondary dashes.
paused: boolean, default False
Whether the animation is running or not.
reverse: boolean, default False
Whether the animation is going backwards or not.
hardware_accelerated: boolean, default False
Whether the ant-path uses hardware acceleration.
radius: int, default 10
Radius of the circle, if use is set to ‘circle’
"""
_view_name = Unicode("LeafletAntPathView").tag(sync=True)
_model_name = Unicode("LeafletAntPathModel").tag(sync=True)
locations = List().tag(sync=True)
# Options
use = Enum(
values=["polyline", "polygon", "rectangle", "circle"], default_value="polyline"
).tag(sync=True, o=True)
delay = Int(400).tag(sync=True, o=True)
weight = Int(5).tag(sync=True, o=True)
dash_array = List([10, 20]).tag(sync=True, o=True)
color = Color("#0000FF").tag(sync=True, o=True)
pulse_color = Color("#FFFFFF").tag(sync=True, o=True)
paused = Bool(False).tag(sync=True, o=True)
reverse = Bool(False).tag(sync=True, o=True)
hardware_accelerated = Bool(False).tag(sync=True, o=True)
radius = Int(10).tag(sync=True, o=True)
| (*args: 't.Any', **kwargs: 't.Any') -> 't.Any' |
11,790 | ipywidgets.widgets.widget | __copy__ | null | def __copy__(self):
raise NotImplementedError("Widgets cannot be copied; custom implementation required")
| (self) |
11,791 | ipywidgets.widgets.widget | __deepcopy__ | null | def __deepcopy__(self, memo):
raise NotImplementedError("Widgets cannot be copied; custom implementation required")
| (self, memo) |
11,792 | ipywidgets.widgets.widget | __del__ | Object disposal | def __del__(self):
"""Object disposal"""
self.close()
| (self) |
11,793 | traitlets.traitlets | __getstate__ | null | def __getstate__(self) -> dict[str, t.Any]:
d = self.__dict__.copy()
# event handlers stored on an instance are
# expected to be reinstantiated during a
# recall of instance_init during __setstate__
d["_trait_notifiers"] = {}
d["_trait_validators"] = {}
d["_trait_values"] = self._trait_values.copy()
d["_cross_validation_lock"] = False # FIXME: raise if cloning locked!
return d
| (self) -> dict[str, typing.Any] |
11,794 | ipyleaflet.leaflet | __init__ | null | def __init__(self, **kwargs):
super(Layer, self).__init__(**kwargs)
self.on_msg(self._handle_mouse_events)
| (self, **kwargs) |
11,795 | traitlets.traitlets | __new__ | null | def __new__(*args: t.Any, **kwargs: t.Any) -> t.Any:
# Pass cls as args[0] to allow "cls" as keyword argument
cls = args[0]
args = args[1:]
# This is needed because object.__new__ only accepts
# the cls argument.
new_meth = super(HasDescriptors, cls).__new__
if new_meth is object.__new__:
inst = new_meth(cls)
else:
inst = new_meth(cls, *args, **kwargs)
inst.setup_instance(*args, **kwargs)
return inst
| (*args: Any, **kwargs: Any) -> Any |
11,796 | ipywidgets.widgets.widget | __repr__ | null | def __repr__(self):
return self._gen_repr_from_keys(self._repr_keys())
| (self) |
11,797 | traitlets.traitlets | __setstate__ | null | def __setstate__(self, state: dict[str, t.Any]) -> None:
self.__dict__ = state.copy()
# event handlers are reassigned to self
cls = self.__class__
for key in dir(cls):
# Some descriptors raise AttributeError like zope.interface's
# __provides__ attributes even though they exist. This causes
# AttributeErrors even though they are listed in dir(cls).
try:
value = getattr(cls, key)
except AttributeError:
pass
else:
if isinstance(value, EventHandler):
value.instance_init(self)
| (self, state: dict[str, typing.Any]) -> NoneType |
11,798 | traitlets.traitlets | _add_notifiers | null | def _add_notifiers(
self, handler: t.Callable[..., t.Any], name: Sentinel | str, type: str | Sentinel
) -> None:
if name not in self._trait_notifiers:
nlist: list[t.Any] = []
self._trait_notifiers[name] = {type: nlist}
else:
if type not in self._trait_notifiers[name]:
nlist = []
self._trait_notifiers[name][type] = nlist
else:
nlist = self._trait_notifiers[name][type]
if handler not in nlist:
nlist.append(handler)
| (self, handler: Callable[..., Any], name: traitlets.utils.sentinel.Sentinel | str, type: str | traitlets.utils.sentinel.Sentinel) -> NoneType |
11,799 | ipywidgets.widgets.widget | _call_widget_constructed | Static method, called when a widget is constructed. | @staticmethod
def _call_widget_constructed(widget):
"""Static method, called when a widget is constructed."""
if Widget._widget_construction_callback is not None and callable(Widget._widget_construction_callback):
Widget._widget_construction_callback(widget)
| (widget) |
11,800 | ipywidgets.widgets.widget | _compare | null | def _compare(self, a, b):
if self._is_numpy(a) or self._is_numpy(b):
import numpy as np
return np.array_equal(a, b)
else:
return a == b
| (self, a, b) |
11,801 | ipywidgets.widgets.widget | _gen_repr_from_keys | null | def _gen_repr_from_keys(self, keys):
class_name = self.__class__.__name__
signature = ', '.join(
'{}={!r}'.format(key, getattr(self, key))
for key in keys
)
return '{}({})'.format(class_name, signature)
| (self, keys) |
11,802 | ipywidgets.widgets.widget | _get_embed_state | null | def _get_embed_state(self, drop_defaults=False):
state = {
'model_name': self._model_name,
'model_module': self._model_module,
'model_module_version': self._model_module_version
}
model_state, buffer_paths, buffers = _remove_buffers(self.get_state(drop_defaults=drop_defaults))
state['state'] = model_state
if len(buffers) > 0:
state['buffers'] = [{'encoding': 'base64',
'path': p,
'data': standard_b64encode(d).decode('ascii')}
for p, d in zip(buffer_paths, buffers)]
return state
| (self, drop_defaults=False) |
11,803 | traitlets.traitlets | _get_trait_default_generator | Return default generator for a given trait
Walk the MRO to resolve the correct default generator according to inheritance.
| def _get_trait_default_generator(self, name: str) -> t.Any:
"""Return default generator for a given trait
Walk the MRO to resolve the correct default generator according to inheritance.
"""
method_name = "_%s_default" % name
if method_name in self.__dict__:
return getattr(self, method_name)
if method_name in self.__class__.__dict__:
return getattr(self.__class__, method_name)
return self._all_trait_default_generators[name]
| (self, name: str) -> Any |
11,804 | ipywidgets.widgets.widget | _handle_custom_msg | Called when a custom msg is received. | def _handle_custom_msg(self, content, buffers):
"""Called when a custom msg is received."""
self._msg_callbacks(self, content, buffers)
| (self, content, buffers) |
11,805 | ipyleaflet.leaflet | _handle_mouse_events | null | def _handle_mouse_events(self, _, content, buffers):
event_type = content.get("type", "")
if event_type == "click":
self._click_callbacks(**content)
if event_type == "dblclick":
self._dblclick_callbacks(**content)
if event_type == "mousedown":
self._mousedown_callbacks(**content)
if event_type == "mouseup":
self._mouseup_callbacks(**content)
if event_type == "mouseover":
self._mouseover_callbacks(**content)
if event_type == "mouseout":
self._mouseout_callbacks(**content)
| (self, _, content, buffers) |
11,806 | ipywidgets.widgets.widget | m | null | def _show_traceback(method):
"""decorator for showing tracebacks"""
def m(self, *args, **kwargs):
try:
return(method(self, *args, **kwargs))
except Exception as e:
ip = get_ipython()
if ip is None:
self.log.warning("Exception in widget method %s: %s", method, e, exc_info=True)
else:
ip.showtraceback()
return m
| (self, *args, **kwargs) |
11,807 | ipywidgets.widgets.widget | _is_numpy | null | def _is_numpy(self, x):
return x.__class__.__name__ == 'ndarray' and x.__class__.__module__ == 'numpy'
| (self, x) |
11,808 | ipywidgets.widgets.widget | _lock_property | Lock a property-value pair.
The value should be the JSON state of the property.
NOTE: This, in addition to the single lock for all state changes, is
flawed. In the future we may want to look into buffering state changes
back to the front-end. | def register(widget):
"""A decorator registering a widget class in the widget registry."""
w = widget.class_traits()
_registry.register(w['_model_module'].default_value,
w['_model_module_version'].default_value,
w['_model_name'].default_value,
w['_view_module'].default_value,
w['_view_module_version'].default_value,
w['_view_name'].default_value,
widget)
return widget
| (self, **properties) |
11,809 | traitlets.traitlets | _notify_observers | Notify observers of any event | def _notify_observers(self, event: Bunch) -> None:
"""Notify observers of any event"""
if not isinstance(event, Bunch):
# cast to bunch if given a dict
event = Bunch(event) # type:ignore[unreachable]
name, type = event["name"], event["type"]
callables = []
if name in self._trait_notifiers:
callables.extend(self._trait_notifiers.get(name, {}).get(type, []))
callables.extend(self._trait_notifiers.get(name, {}).get(All, []))
if All in self._trait_notifiers:
callables.extend(self._trait_notifiers.get(All, {}).get(type, []))
callables.extend(self._trait_notifiers.get(All, {}).get(All, []))
# Now static ones
magic_name = "_%s_changed" % name
if event["type"] == "change" and hasattr(self, magic_name):
class_value = getattr(self.__class__, magic_name)
if not isinstance(class_value, ObserveHandler):
deprecated_method(
class_value,
self.__class__,
magic_name,
"use @observe and @unobserve instead.",
)
cb = getattr(self, magic_name)
# Only append the magic method if it was not manually registered
if cb not in callables:
callables.append(_callback_wrapper(cb))
# Call them all now
# Traits catches and logs errors here. I allow them to raise
for c in callables:
# Bound methods have an additional 'self' argument.
if isinstance(c, _CallbackWrapper):
c = c.__call__
elif isinstance(c, EventHandler) and c.name is not None:
c = getattr(self, c.name)
c(event)
| (self, event: traitlets.utils.bunch.Bunch) -> NoneType |
11,810 | traitlets.traitlets | _notify_trait | null | def _notify_trait(self, name: str, old_value: t.Any, new_value: t.Any) -> None:
self.notify_change(
Bunch(
name=name,
old=old_value,
new=new_value,
owner=self,
type="change",
)
)
| (self, name: str, old_value: Any, new_value: Any) -> NoneType |
11,811 | traitlets.traitlets | _register_validator | Setup a handler to be called when a trait should be cross validated.
This is used to setup dynamic notifications for cross-validation.
If a validator is already registered for any of the provided names, a
TraitError is raised and no new validator is registered.
Parameters
----------
handler : callable
A callable that is called when the given trait is cross-validated.
Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
with the following attributes/keys:
* ``owner`` : the HasTraits instance
* ``value`` : the proposed value for the modified trait attribute
* ``trait`` : the TraitType instance associated with the attribute
names : List of strings
The names of the traits that should be cross-validated
| def _register_validator(
self, handler: t.Callable[..., None], names: tuple[str | Sentinel, ...]
) -> None:
"""Setup a handler to be called when a trait should be cross validated.
This is used to setup dynamic notifications for cross-validation.
If a validator is already registered for any of the provided names, a
TraitError is raised and no new validator is registered.
Parameters
----------
handler : callable
A callable that is called when the given trait is cross-validated.
Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
with the following attributes/keys:
* ``owner`` : the HasTraits instance
* ``value`` : the proposed value for the modified trait attribute
* ``trait`` : the TraitType instance associated with the attribute
names : List of strings
The names of the traits that should be cross-validated
"""
for name in names:
magic_name = "_%s_validate" % name
if hasattr(self, magic_name):
class_value = getattr(self.__class__, magic_name)
if not isinstance(class_value, ValidateHandler):
deprecated_method(
class_value,
self.__class__,
magic_name,
"use @validate decorator instead.",
)
for name in names:
self._trait_validators[name] = handler
| (self, handler: Callable[..., NoneType], names: tuple[str | traitlets.utils.sentinel.Sentinel, ...]) -> NoneType |
11,812 | traitlets.traitlets | _remove_notifiers | null | def _remove_notifiers(
self, handler: t.Callable[..., t.Any] | None, name: Sentinel | str, type: str | Sentinel
) -> None:
try:
if handler is None:
del self._trait_notifiers[name][type]
else:
self._trait_notifiers[name][type].remove(handler)
except KeyError:
pass
| (self, handler: Optional[Callable[..., Any]], name: traitlets.utils.sentinel.Sentinel | str, type: str | traitlets.utils.sentinel.Sentinel) -> NoneType |
11,813 | ipywidgets.widgets.widget | _repr_keys | null | def _repr_keys(self):
traits = self.traits()
for key in sorted(self.keys):
# Exclude traits that start with an underscore
if key[0] == '_':
continue
# Exclude traits who are equal to their default value
value = getattr(self, key)
trait = traits[key]
if self._compare(value, trait.default_value):
continue
elif (isinstance(trait, (Container, Dict)) and
trait.default_value == Undefined and
(value is None or len(value) == 0)):
# Empty container, and dynamic default will be empty
continue
yield key
| (self) |
11,814 | ipywidgets.widgets.widget | _repr_mimebundle_ | null | def _repr_mimebundle_(self, **kwargs):
plaintext = repr(self)
if len(plaintext) > 110:
plaintext = plaintext[:110] + '…'
data = {
'text/plain': plaintext,
}
if self._view_name is not None:
# The 'application/vnd.jupyter.widget-view+json' mimetype has not been registered yet.
# See the registration process and naming convention at
# http://tools.ietf.org/html/rfc6838
# and the currently registered mimetypes at
# http://www.iana.org/assignments/media-types/media-types.xhtml.
data['application/vnd.jupyter.widget-view+json'] = {
'version_major': 2,
'version_minor': 0,
'model_id': self._model_id
}
return data
| (self, **kwargs) |
11,815 | ipywidgets.widgets.widget | _send | Sends a message to the model in the front-end. | def _send(self, msg, buffers=None):
"""Sends a message to the model in the front-end."""
if self.comm is not None and (self.comm.kernel is not None if hasattr(self.comm, "kernel") else True):
self.comm.send(data=msg, buffers=buffers)
| (self, msg, buffers=None) |
11,816 | ipywidgets.widgets.widget | _should_send_property | Check the property lock (property_lock) | def _should_send_property(self, key, value):
"""Check the property lock (property_lock)"""
to_json = self.trait_metadata(key, 'to_json', self._trait_to_json)
if key in self._property_lock:
# model_state, buffer_paths, buffers
split_value = _remove_buffers({ key: to_json(value, self)})
split_lock = _remove_buffers({ key: self._property_lock[key]})
# A roundtrip conversion through json in the comparison takes care of
# idiosyncracies of how python data structures map to json, for example
# tuples get converted to lists.
if (jsonloads(jsondumps(split_value[0])) == split_lock[0]
and split_value[1] == split_lock[1]
and _buffer_list_equal(split_value[2], split_lock[2])):
if self._holding_sync:
self._states_to_send.discard(key)
return False
if self._holding_sync:
self._states_to_send.add(key)
return False
else:
return True
| (self, key, value) |
11,817 | ipywidgets.widgets.widget | _trait_from_json | Convert json values to objects. | @staticmethod
def _trait_from_json(x, self):
"""Convert json values to objects."""
return x
| (x, self) |
11,818 | ipywidgets.widgets.widget | _trait_to_json | Convert a trait value to json. | @staticmethod
def _trait_to_json(x, self):
"""Convert a trait value to json."""
return x
| (x, self) |
11,819 | ipywidgets.widgets.widget | add_traits | Dynamically add trait attributes to the Widget. | def add_traits(self, **traits):
"""Dynamically add trait attributes to the Widget."""
super().add_traits(**traits)
for name, trait in traits.items():
if trait.get_metadata('sync'):
self.keys.append(name)
self.send_state(name)
| (self, **traits) |
11,820 | ipywidgets.widgets.widget | close | Close method.
Closes the underlying comm.
When the comm is closed, all of the widget views are automatically
removed from the front-end. | def close(self):
"""Close method.
Closes the underlying comm.
When the comm is closed, all of the widget views are automatically
removed from the front-end."""
if self.comm is not None:
_instances.pop(self.model_id, None)
self.comm.close()
self.comm = None
self._repr_mimebundle_ = None
| (self) |
11,821 | ipywidgets.widgets.widget | get_manager_state | Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
:return:
| @staticmethod
def get_manager_state(drop_defaults=False, widgets=None):
"""Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
:return:
"""
state = {}
if widgets is None:
widgets = _instances.values()
for widget in widgets:
state[widget.model_id] = widget._get_embed_state(drop_defaults=drop_defaults)
return {'version_major': 2, 'version_minor': 0, 'state': state}
| (drop_defaults=False, widgets=None) |
11,822 | ipywidgets.widgets.widget | get_state | Gets the widget state, or a piece of it.
Parameters
----------
key : unicode or iterable (optional)
A single property's name or iterable of property names to get.
Returns
-------
state : dict of states
metadata : dict
metadata for each field: {key: metadata}
| def get_state(self, key=None, drop_defaults=False):
"""Gets the widget state, or a piece of it.
Parameters
----------
key : unicode or iterable (optional)
A single property's name or iterable of property names to get.
Returns
-------
state : dict of states
metadata : dict
metadata for each field: {key: metadata}
"""
if key is None:
keys = self.keys
elif isinstance(key, str):
keys = [key]
elif isinstance(key, Iterable):
keys = key
else:
raise ValueError("key must be a string, an iterable of keys, or None")
state = {}
traits = self.traits()
for k in keys:
to_json = self.trait_metadata(k, 'to_json', self._trait_to_json)
value = to_json(getattr(self, k), self)
if not drop_defaults or not self._compare(value, traits[k].default_value):
state[k] = value
return state
| (self, key=None, drop_defaults=False) |
11,823 | ipywidgets.widgets.widget | get_view_spec | null | def get_view_spec(self):
return dict(version_major=2, version_minor=0, model_id=self._model_id)
| (self) |
11,824 | ipywidgets.widgets.widget | handle_comm_opened | Static method, called when a widget is constructed. | @staticmethod
def handle_comm_opened(comm, msg):
"""Static method, called when a widget is constructed."""
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != PROTOCOL_VERSION_MAJOR:
raise ValueError("Incompatible widget protocol versions: received version %r, expected version %r"%(version, __protocol_version__))
data = msg['content']['data']
state = data['state']
# Find the widget class to instantiate in the registered widgets
widget_class = _registry.get(state['_model_module'],
state['_model_module_version'],
state['_model_name'],
state['_view_module'],
state['_view_module_version'],
state['_view_name'])
widget = widget_class(comm=comm)
if 'buffer_paths' in data:
_put_buffers(state, data['buffer_paths'], msg['buffers'])
widget.set_state(state)
| (comm, msg) |
11,825 | traitlets.traitlets | has_trait | Returns True if the object has a trait with the specified name. | def has_trait(self, name: str) -> bool:
"""Returns True if the object has a trait with the specified name."""
return name in self._traits
| (self, name: str) -> bool |
11,826 | ipywidgets.widgets.widget | hold_sync | Hold syncing any state until the outermost context manager exits | def register(widget):
"""A decorator registering a widget class in the widget registry."""
w = widget.class_traits()
_registry.register(w['_model_module'].default_value,
w['_model_module_version'].default_value,
w['_model_name'].default_value,
w['_view_module'].default_value,
w['_view_module_version'].default_value,
w['_view_name'].default_value,
widget)
return widget
| (self) |
11,827 | traitlets.traitlets | hold_trait_notifications | Context manager for bundling trait change notifications and cross
validation.
Use this when doing multiple trait assignments (init, config), to avoid
race conditions in trait notifiers requesting other trait values.
All trait notifications will fire after all values have been assigned.
| def _validate_link(*tuples: t.Any) -> None:
"""Validate arguments for traitlet link functions"""
for tup in tuples:
if not len(tup) == 2:
raise TypeError(
"Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t
)
obj, trait_name = tup
if not isinstance(obj, HasTraits):
raise TypeError("Each object must be HasTraits, not %r" % type(obj))
if trait_name not in obj.traits():
raise TypeError(f"{obj!r} has no trait {trait_name!r}")
| (self) -> Any |
11,828 | ipyleaflet.leaflet | interact | null | def interact(self, **kwargs):
c = []
for name, abbrev in kwargs.items():
default = getattr(self, name)
widget = interactive.widget_from_abbrev(abbrev, default)
if not widget.description:
widget.description = name
widget.link = link((widget, "value"), (self, name))
c.append(widget)
cont = Box(children=c)
return cont
| (self, **kwargs) |
11,829 | ipywidgets.widgets.widget | notify_change | Called when a property has changed. | def notify_change(self, change):
"""Called when a property has changed."""
# Send the state to the frontend before the user-registered callbacks
# are called.
name = change['name']
if self.comm is not None and getattr(self.comm, 'kernel', True) is not None:
# Make sure this isn't information that the front-end just sent us.
if name in self.keys and self._should_send_property(name, getattr(self, name)):
# Send new state to front-end
self.send_state(key=name)
super().notify_change(change)
| (self, change) |
11,830 | traitlets.traitlets | observe | Setup a handler to be called when a trait changes.
This is used to setup dynamic notifications of trait changes.
Parameters
----------
handler : callable
A callable that is called when a trait changes. Its
signature should be ``handler(change)``, where ``change`` is a
dictionary. The change dictionary at least holds a 'type' key.
* ``type``: the type of notification.
Other keys may be passed depending on the value of 'type'. In the
case where type is 'change', we also have the following keys:
* ``owner`` : the HasTraits instance
* ``old`` : the old value of the modified trait attribute
* ``new`` : the new value of the modified trait attribute
* ``name`` : the name of the modified trait attribute.
names : list, str, All
If names is All, the handler will apply to all traits. If a list
of str, handler will apply to all names in the list. If a
str, the handler will apply just to that name.
type : str, All (default: 'change')
The type of notification to filter by. If equal to All, then all
notifications are passed to the observe handler.
| def observe(
self,
handler: t.Callable[..., t.Any],
names: Sentinel | str | t.Iterable[Sentinel | str] = All,
type: Sentinel | str = "change",
) -> None:
"""Setup a handler to be called when a trait changes.
This is used to setup dynamic notifications of trait changes.
Parameters
----------
handler : callable
A callable that is called when a trait changes. Its
signature should be ``handler(change)``, where ``change`` is a
dictionary. The change dictionary at least holds a 'type' key.
* ``type``: the type of notification.
Other keys may be passed depending on the value of 'type'. In the
case where type is 'change', we also have the following keys:
* ``owner`` : the HasTraits instance
* ``old`` : the old value of the modified trait attribute
* ``new`` : the new value of the modified trait attribute
* ``name`` : the name of the modified trait attribute.
names : list, str, All
If names is All, the handler will apply to all traits. If a list
of str, handler will apply to all names in the list. If a
str, the handler will apply just to that name.
type : str, All (default: 'change')
The type of notification to filter by. If equal to All, then all
notifications are passed to the observe handler.
"""
for name in parse_notifier_name(names):
self._add_notifiers(handler, name, type)
| (self, handler: Callable[..., Any], names: Union[traitlets.utils.sentinel.Sentinel, str, Iterable[traitlets.utils.sentinel.Sentinel | str]] = traitlets.All, type: traitlets.utils.sentinel.Sentinel | str = 'change') -> NoneType |
11,831 | ipyleaflet.leaflet | on_click | Add a click event listener.
Parameters
----------
callback : callable
Callback function that will be called on click event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
| def on_click(self, callback, remove=False):
"""Add a click event listener.
Parameters
----------
callback : callable
Callback function that will be called on click event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._click_callbacks.register_callback(callback, remove=remove)
| (self, callback, remove=False) |
11,832 | ipyleaflet.leaflet | on_dblclick | Add a double-click event listener.
Parameters
----------
callback : callable
Callback function that will be called on double-click event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
| def on_dblclick(self, callback, remove=False):
"""Add a double-click event listener.
Parameters
----------
callback : callable
Callback function that will be called on double-click event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._dblclick_callbacks.register_callback(callback, remove=remove)
| (self, callback, remove=False) |
11,833 | ipyleaflet.leaflet | on_mousedown | Add a mouse-down event listener.
Parameters
----------
callback : callable
Callback function that will be called on mouse-down event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
| def on_mousedown(self, callback, remove=False):
"""Add a mouse-down event listener.
Parameters
----------
callback : callable
Callback function that will be called on mouse-down event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._mousedown_callbacks.register_callback(callback, remove=remove)
| (self, callback, remove=False) |
11,834 | ipyleaflet.leaflet | on_mouseout | Add a mouse-out event listener.
Parameters
----------
callback : callable
Callback function that will be called on mouse-out event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
| def on_mouseout(self, callback, remove=False):
"""Add a mouse-out event listener.
Parameters
----------
callback : callable
Callback function that will be called on mouse-out event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._mouseout_callbacks.register_callback(callback, remove=remove)
| (self, callback, remove=False) |
11,835 | ipyleaflet.leaflet | on_mouseover | Add a mouse-over event listener.
Parameters
----------
callback : callable
Callback function that will be called on mouse-over event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
| def on_mouseover(self, callback, remove=False):
"""Add a mouse-over event listener.
Parameters
----------
callback : callable
Callback function that will be called on mouse-over event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._mouseover_callbacks.register_callback(callback, remove=remove)
| (self, callback, remove=False) |
11,836 | ipyleaflet.leaflet | on_mouseup | Add a mouse-up event listener.
Parameters
----------
callback : callable
Callback function that will be called on mouse-up event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
| def on_mouseup(self, callback, remove=False):
"""Add a mouse-up event listener.
Parameters
----------
callback : callable
Callback function that will be called on mouse-up event.
remove: boolean
Whether to remove this callback or not. Defaults to False.
"""
self._mouseup_callbacks.register_callback(callback, remove=remove)
| (self, callback, remove=False) |
11,837 | ipywidgets.widgets.widget | on_msg | (Un)Register a custom msg receive callback.
Parameters
----------
callback: callable
callback will be passed three arguments when a message arrives::
callback(widget, content, buffers)
remove: bool
True if the callback should be unregistered. | def on_msg(self, callback, remove=False):
"""(Un)Register a custom msg receive callback.
Parameters
----------
callback: callable
callback will be passed three arguments when a message arrives::
callback(widget, content, buffers)
remove: bool
True if the callback should be unregistered."""
self._msg_callbacks.register_callback(callback, remove=remove)
| (self, callback, remove=False) |
11,838 | traitlets.traitlets | on_trait_change | DEPRECATED: Setup a handler to be called when a trait changes.
This is used to setup dynamic notifications of trait changes.
Static handlers can be created by creating methods on a HasTraits
subclass with the naming convention '_[traitname]_changed'. Thus,
to create static handler for the trait 'a', create the method
_a_changed(self, name, old, new) (fewer arguments can be used, see
below).
If `remove` is True and `handler` is not specified, all change
handlers for the specified name are uninstalled.
Parameters
----------
handler : callable, None
A callable that is called when a trait changes. Its
signature can be handler(), handler(name), handler(name, new),
handler(name, old, new), or handler(name, old, new, self).
name : list, str, None
If None, the handler will apply to all traits. If a list
of str, handler will apply to all names in the list. If a
str, the handler will apply just to that name.
remove : bool
If False (the default), then install the handler. If True
then unintall it.
| def on_trait_change(
self,
handler: EventHandler | None = None,
name: Sentinel | str | None = None,
remove: bool = False,
) -> None:
"""DEPRECATED: Setup a handler to be called when a trait changes.
This is used to setup dynamic notifications of trait changes.
Static handlers can be created by creating methods on a HasTraits
subclass with the naming convention '_[traitname]_changed'. Thus,
to create static handler for the trait 'a', create the method
_a_changed(self, name, old, new) (fewer arguments can be used, see
below).
If `remove` is True and `handler` is not specified, all change
handlers for the specified name are uninstalled.
Parameters
----------
handler : callable, None
A callable that is called when a trait changes. Its
signature can be handler(), handler(name), handler(name, new),
handler(name, old, new), or handler(name, old, new, self).
name : list, str, None
If None, the handler will apply to all traits. If a list
of str, handler will apply to all names in the list. If a
str, the handler will apply just to that name.
remove : bool
If False (the default), then install the handler. If True
then unintall it.
"""
warn(
"on_trait_change is deprecated in traitlets 4.1: use observe instead",
DeprecationWarning,
stacklevel=2,
)
if name is None:
name = All
if remove:
self.unobserve(_callback_wrapper(handler), names=name)
else:
self.observe(_callback_wrapper(handler), names=name)
| (self, handler: Optional[traitlets.traitlets.EventHandler] = None, name: Union[traitlets.utils.sentinel.Sentinel, str, NoneType] = None, remove: bool = False) -> NoneType |
11,839 | ipywidgets.widgets.widget | on_widget_constructed | Registers a callback to be called when a widget is constructed.
The callback must have the following signature:
callback(widget) | @staticmethod
def on_widget_constructed(callback):
"""Registers a callback to be called when a widget is constructed.
The callback must have the following signature:
callback(widget)"""
Widget._widget_construction_callback = callback
| (callback) |
11,840 | ipywidgets.widgets.widget | open | Open a comm to the frontend if one isn't already open. | def open(self):
"""Open a comm to the frontend if one isn't already open."""
if self.comm is None:
state, buffer_paths, buffers = _remove_buffers(self.get_state())
args = dict(target_name='jupyter.widget',
data={'state': state, 'buffer_paths': buffer_paths},
buffers=buffers,
metadata={'version': __protocol_version__}
)
if self._model_id is not None:
args['comm_id'] = self._model_id
self.comm = comm.create_comm(**args)
| (self) |
11,841 | ipywidgets.widgets.widget | send | Sends a custom msg to the widget model in the front-end.
Parameters
----------
content : dict
Content of the message to send.
buffers : list of binary buffers
Binary buffers to send with message
| def send(self, content, buffers=None):
"""Sends a custom msg to the widget model in the front-end.
Parameters
----------
content : dict
Content of the message to send.
buffers : list of binary buffers
Binary buffers to send with message
"""
self._send({"method": "custom", "content": content}, buffers=buffers)
| (self, content, buffers=None) |
11,842 | ipywidgets.widgets.widget | send_state | Sends the widget state, or a piece of it, to the front-end, if it exists.
Parameters
----------
key : unicode, or iterable (optional)
A single property's name or iterable of property names to sync with the front-end.
| def send_state(self, key=None):
"""Sends the widget state, or a piece of it, to the front-end, if it exists.
Parameters
----------
key : unicode, or iterable (optional)
A single property's name or iterable of property names to sync with the front-end.
"""
state = self.get_state(key=key)
if len(state) > 0:
if self._property_lock: # we need to keep this dict up to date with the front-end values
for name, value in state.items():
if name in self._property_lock:
self._property_lock[name] = value
state, buffer_paths, buffers = _remove_buffers(state)
msg = {'method': 'update', 'state': state, 'buffer_paths': buffer_paths}
self._send(msg, buffers=buffers)
| (self, key=None) |
11,843 | ipywidgets.widgets.widget | set_state | Called when a state is received from the front-end. | def set_state(self, sync_data):
"""Called when a state is received from the front-end."""
# Send an echo update message immediately
if JUPYTER_WIDGETS_ECHO:
echo_state = {}
for attr, value in sync_data.items():
if attr in self.keys and self.trait_metadata(attr, 'echo_update', default=True):
echo_state[attr] = value
if echo_state:
echo_state, echo_buffer_paths, echo_buffers = _remove_buffers(echo_state)
msg = {
'method': 'echo_update',
'state': echo_state,
'buffer_paths': echo_buffer_paths,
}
self._send(msg, buffers=echo_buffers)
# The order of these context managers is important. Properties must
# be locked when the hold_trait_notification context manager is
# released and notifications are fired.
with self._lock_property(**sync_data), self.hold_trait_notifications():
for name in sync_data:
if name in self.keys:
from_json = self.trait_metadata(name, 'from_json',
self._trait_from_json)
self.set_trait(name, from_json(sync_data[name], self))
| (self, sync_data) |
11,844 | traitlets.traitlets | set_trait | Forcibly sets trait attribute, including read-only attributes. | def set_trait(self, name: str, value: t.Any) -> None:
"""Forcibly sets trait attribute, including read-only attributes."""
cls = self.__class__
if not self.has_trait(name):
raise TraitError(f"Class {cls.__name__} does not have a trait named {name}")
getattr(cls, name).set(self, value)
| (self, name: str, value: Any) -> NoneType |
11,845 | traitlets.traitlets | setup_instance | null | def setup_instance(*args: t.Any, **kwargs: t.Any) -> None:
# Pass self as args[0] to allow "self" as keyword argument
self = args[0]
args = args[1:]
# although we'd prefer to set only the initial values not present
# in kwargs, we will overwrite them in `__init__`, and simply making
# a copy of a dict is faster than checking for each key.
self._trait_values = self._static_immutable_initial_values.copy()
self._trait_notifiers = {}
self._trait_validators = {}
self._cross_validation_lock = False
super(HasTraits, self).setup_instance(*args, **kwargs)
| (*args: Any, **kwargs: Any) -> NoneType |
11,846 | traitlets.traitlets | trait_defaults | Return a trait's default value or a dictionary of them
Notes
-----
Dynamically generated default values may
depend on the current state of the object. | def trait_defaults(self, *names: str, **metadata: t.Any) -> dict[str, t.Any] | Sentinel:
"""Return a trait's default value or a dictionary of them
Notes
-----
Dynamically generated default values may
depend on the current state of the object."""
for n in names:
if not self.has_trait(n):
raise TraitError(f"'{n}' is not a trait of '{type(self).__name__}' instances")
if len(names) == 1 and len(metadata) == 0:
return t.cast(Sentinel, self._get_trait_default_generator(names[0])(self))
trait_names = self.trait_names(**metadata)
trait_names.extend(names)
defaults = {}
for n in trait_names:
defaults[n] = self._get_trait_default_generator(n)(self)
return defaults
| (self, *names: str, **metadata: Any) -> dict[str, typing.Any] | traitlets.utils.sentinel.Sentinel |
11,847 | traitlets.traitlets | trait_has_value | Returns True if the specified trait has a value.
This will return false even if ``getattr`` would return a
dynamically generated default value. These default values
will be recognized as existing only after they have been
generated.
Example
.. code-block:: python
class MyClass(HasTraits):
i = Int()
mc = MyClass()
assert not mc.trait_has_value("i")
mc.i # generates a default value
assert mc.trait_has_value("i")
| def trait_has_value(self, name: str) -> bool:
"""Returns True if the specified trait has a value.
This will return false even if ``getattr`` would return a
dynamically generated default value. These default values
will be recognized as existing only after they have been
generated.
Example
.. code-block:: python
class MyClass(HasTraits):
i = Int()
mc = MyClass()
assert not mc.trait_has_value("i")
mc.i # generates a default value
assert mc.trait_has_value("i")
"""
return name in self._trait_values
| (self, name: str) -> bool |
11,848 | traitlets.traitlets | trait_metadata | Get metadata values for trait by key. | def trait_metadata(self, traitname: str, key: str, default: t.Any = None) -> t.Any:
"""Get metadata values for trait by key."""
try:
trait = getattr(self.__class__, traitname)
except AttributeError as e:
raise TraitError(
f"Class {self.__class__.__name__} does not have a trait named {traitname}"
) from e
metadata_name = "_" + traitname + "_metadata"
if hasattr(self, metadata_name) and key in getattr(self, metadata_name):
return getattr(self, metadata_name).get(key, default)
else:
return trait.metadata.get(key, default)
| (self, traitname: str, key: str, default: Optional[Any] = None) -> Any |
11,849 | traitlets.traitlets | trait_names | Get a list of all the names of this class' traits. | def trait_names(self, **metadata: t.Any) -> list[str]:
"""Get a list of all the names of this class' traits."""
return list(self.traits(**metadata))
| (self, **metadata: Any) -> list[str] |
11,850 | traitlets.traitlets | trait_values | A ``dict`` of trait names and their values.
The metadata kwargs allow functions to be passed in which
filter traits based on metadata values. The functions should
take a single value as an argument and return a boolean. If
any function returns False, then the trait is not included in
the output. If a metadata key doesn't exist, None will be passed
to the function.
Returns
-------
A ``dict`` of trait names and their values.
Notes
-----
Trait values are retrieved via ``getattr``, any exceptions raised
by traits or the operations they may trigger will result in the
absence of a trait value in the result ``dict``.
| def trait_values(self, **metadata: t.Any) -> dict[str, t.Any]:
"""A ``dict`` of trait names and their values.
The metadata kwargs allow functions to be passed in which
filter traits based on metadata values. The functions should
take a single value as an argument and return a boolean. If
any function returns False, then the trait is not included in
the output. If a metadata key doesn't exist, None will be passed
to the function.
Returns
-------
A ``dict`` of trait names and their values.
Notes
-----
Trait values are retrieved via ``getattr``, any exceptions raised
by traits or the operations they may trigger will result in the
absence of a trait value in the result ``dict``.
"""
return {name: getattr(self, name) for name in self.trait_names(**metadata)}
| (self, **metadata: Any) -> dict[str, typing.Any] |
11,851 | traitlets.traitlets | traits | Get a ``dict`` of all the traits of this class. The dictionary
is keyed on the name and the values are the TraitType objects.
The TraitTypes returned don't know anything about the values
that the various HasTrait's instances are holding.
The metadata kwargs allow functions to be passed in which
filter traits based on metadata values. The functions should
take a single value as an argument and return a boolean. If
any function returns False, then the trait is not included in
the output. If a metadata key doesn't exist, None will be passed
to the function.
| def traits(self, **metadata: t.Any) -> dict[str, TraitType[t.Any, t.Any]]:
"""Get a ``dict`` of all the traits of this class. The dictionary
is keyed on the name and the values are the TraitType objects.
The TraitTypes returned don't know anything about the values
that the various HasTrait's instances are holding.
The metadata kwargs allow functions to be passed in which
filter traits based on metadata values. The functions should
take a single value as an argument and return a boolean. If
any function returns False, then the trait is not included in
the output. If a metadata key doesn't exist, None will be passed
to the function.
"""
traits = self._traits.copy()
if len(metadata) == 0:
return traits
result = {}
for name, trait in traits.items():
for meta_name, meta_eval in metadata.items():
if not callable(meta_eval):
meta_eval = _SimpleTest(meta_eval)
if not meta_eval(trait.metadata.get(meta_name, None)):
break
else:
result[name] = trait
return result
| (self, **metadata: Any) -> dict[str, traitlets.traitlets.TraitType[typing.Any, typing.Any]] |
11,852 | traitlets.traitlets | unobserve | Remove a trait change handler.
This is used to unregister handlers to trait change notifications.
Parameters
----------
handler : callable
The callable called when a trait attribute changes.
names : list, str, All (default: All)
The names of the traits for which the specified handler should be
uninstalled. If names is All, the specified handler is uninstalled
from the list of notifiers corresponding to all changes.
type : str or All (default: 'change')
The type of notification to filter by. If All, the specified handler
is uninstalled from the list of notifiers corresponding to all types.
| def unobserve(
self,
handler: t.Callable[..., t.Any],
names: Sentinel | str | t.Iterable[Sentinel | str] = All,
type: Sentinel | str = "change",
) -> None:
"""Remove a trait change handler.
This is used to unregister handlers to trait change notifications.
Parameters
----------
handler : callable
The callable called when a trait attribute changes.
names : list, str, All (default: All)
The names of the traits for which the specified handler should be
uninstalled. If names is All, the specified handler is uninstalled
from the list of notifiers corresponding to all changes.
type : str or All (default: 'change')
The type of notification to filter by. If All, the specified handler
is uninstalled from the list of notifiers corresponding to all types.
"""
for name in parse_notifier_name(names):
self._remove_notifiers(handler, name, type)
| (self, handler: Callable[..., Any], names: Union[traitlets.utils.sentinel.Sentinel, str, Iterable[traitlets.utils.sentinel.Sentinel | str]] = traitlets.All, type: traitlets.utils.sentinel.Sentinel | str = 'change') -> NoneType |
11,853 | traitlets.traitlets | unobserve_all | Remove trait change handlers of any type for the specified name.
If name is not specified, removes all trait notifiers. | def unobserve_all(self, name: str | t.Any = All) -> None:
"""Remove trait change handlers of any type for the specified name.
If name is not specified, removes all trait notifiers."""
if name is All:
self._trait_notifiers = {}
else:
try:
del self._trait_notifiers[name]
except KeyError:
pass
| (self, name: Union[str, Any] = traitlets.All) -> NoneType |
11,854 | traitlets.traitlets | Any | A trait which allows any value. | class Any(TraitType[t.Optional[t.Any], t.Optional[t.Any]]):
"""A trait which allows any value."""
if t.TYPE_CHECKING:
@t.overload
def __init__(
self: Any,
default_value: t.Any = ...,
*,
allow_none: Literal[False],
read_only: bool | None = ...,
help: str | None = ...,
config: t.Any | None = ...,
**kwargs: t.Any,
) -> None:
...
@t.overload
def __init__(
self: Any,
default_value: t.Any = ...,
*,
allow_none: Literal[True],
read_only: bool | None = ...,
help: str | None = ...,
config: t.Any | None = ...,
**kwargs: t.Any,
) -> None:
...
@t.overload
def __init__(
self: Any,
default_value: t.Any = ...,
*,
allow_none: Literal[True, False] = ...,
help: str | None = ...,
read_only: bool | None = False,
config: t.Any = None,
**kwargs: t.Any,
) -> None:
...
def __init__(
self: Any,
default_value: t.Any = ...,
*,
allow_none: bool = False,
help: str | None = "",
read_only: bool | None = False,
config: t.Any = None,
**kwargs: t.Any,
) -> None:
...
@t.overload
def __get__(self, obj: None, cls: type[t.Any]) -> Any:
...
@t.overload
def __get__(self, obj: t.Any, cls: type[t.Any]) -> t.Any:
...
def __get__(self, obj: t.Any | None, cls: type[t.Any]) -> t.Any | Any:
...
default_value: t.Any | None = None
allow_none = True
info_text = "any value"
def subclass_init(self, cls: type[t.Any]) -> None:
pass # fully opt out of instance_init
| (default_value: Optional[Any] = traitlets.Undefined, allow_none: bool = False, read_only: bool = None, help: 'str | None' = None, config: 't.Any' = None, **kwargs: 't.Any') -> 'None' |
11,855 | traitlets.traitlets | __get__ | Get the value of the trait by self.name for the instance.
Default values are instantiated when :meth:`HasTraits.__new__`
is called. Thus by the time this method gets called either the
default value or a user defined value (they called :meth:`__set__`)
is in the :class:`HasTraits` instance.
| def __get__(self, obj: HasTraits | None, cls: type[t.Any]) -> Self | G:
"""Get the value of the trait by self.name for the instance.
Default values are instantiated when :meth:`HasTraits.__new__`
is called. Thus by the time this method gets called either the
default value or a user defined value (they called :meth:`__set__`)
is in the :class:`HasTraits` instance.
"""
if obj is None:
return self
else:
return t.cast(G, self.get(obj, cls)) # the G should encode the Optional
| (self, obj: 'HasTraits | None', cls: 'type[t.Any]') -> 'Self | G' |
11,856 | traitlets.traitlets | __init__ | Declare a traitlet.
If *allow_none* is True, None is a valid value in addition to any
values that are normally valid. The default is up to the subclass.
For most trait types, the default value for ``allow_none`` is False.
If *read_only* is True, attempts to directly modify a trait attribute raises a TraitError.
If *help* is a string, it documents the attribute's purpose.
Extra metadata can be associated with the traitlet using the .tag() convenience method
or by using the traitlet instance's .metadata dictionary.
| def __init__(
self: TraitType[G, S],
default_value: t.Any = Undefined,
allow_none: bool = False,
read_only: bool | None = None,
help: str | None = None,
config: t.Any = None,
**kwargs: t.Any,
) -> None:
"""Declare a traitlet.
If *allow_none* is True, None is a valid value in addition to any
values that are normally valid. The default is up to the subclass.
For most trait types, the default value for ``allow_none`` is False.
If *read_only* is True, attempts to directly modify a trait attribute raises a TraitError.
If *help* is a string, it documents the attribute's purpose.
Extra metadata can be associated with the traitlet using the .tag() convenience method
or by using the traitlet instance's .metadata dictionary.
"""
if default_value is not Undefined:
self.default_value = default_value
if allow_none:
self.allow_none = allow_none
if read_only is not None:
self.read_only = read_only
self.help = help if help is not None else ""
if self.help:
# define __doc__ so that inspectors like autodoc find traits
self.__doc__ = self.help
if len(kwargs) > 0:
stacklevel = 1
f = inspect.currentframe()
# count supers to determine stacklevel for warning
assert f is not None
while f.f_code.co_name == "__init__":
stacklevel += 1
f = f.f_back
assert f is not None
mod = f.f_globals.get("__name__") or ""
pkg = mod.split(".", 1)[0]
key = ("metadata-tag", pkg, *sorted(kwargs))
if should_warn(key):
warn(
f"metadata {kwargs} was set from the constructor. "
"With traitlets 4.1, metadata should be set using the .tag() method, "
"e.g., Int().tag(key1='value1', key2='value2')",
DeprecationWarning,
stacklevel=stacklevel,
)
if len(self.metadata) > 0:
self.metadata = self.metadata.copy()
self.metadata.update(kwargs)
else:
self.metadata = kwargs
else:
self.metadata = self.metadata.copy()
if config is not None:
self.metadata["config"] = config
# We add help to the metadata during a deprecation period so that
# code that looks for the help string there can find it.
if help is not None:
self.metadata["help"] = help
| (self: traitlets.traitlets.TraitType[~G, ~S], default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: Optional[bool] = None, help: Optional[str] = None, config: Optional[Any] = None, **kwargs: Any) -> NoneType |
11,857 | traitlets.traitlets | __or__ | null | def __or__(self, other: TraitType[t.Any, t.Any]) -> Union:
if isinstance(other, Union):
return Union([self, *other.trait_types])
else:
return Union([self, other])
| (self, other: traitlets.traitlets.TraitType[typing.Any, typing.Any]) -> traitlets.traitlets.Union |
11,858 | traitlets.traitlets | __set__ | Set the value of the trait by self.name for the instance.
Values pass through a validation stage where errors are raised when
impropper types, or types that cannot be coerced, are encountered.
| def __set__(self, obj: HasTraits, value: S) -> None:
"""Set the value of the trait by self.name for the instance.
Values pass through a validation stage where errors are raised when
impropper types, or types that cannot be coerced, are encountered.
"""
if self.read_only:
raise TraitError('The "%s" trait is read-only.' % self.name)
self.set(obj, value)
| (self, obj: traitlets.traitlets.HasTraits, value: ~S) -> NoneType |
11,859 | traitlets.traitlets | _cross_validate | null | def _cross_validate(self, obj: t.Any, value: t.Any) -> G | None:
if self.name in obj._trait_validators:
proposal = Bunch({"trait": self, "value": value, "owner": obj})
value = obj._trait_validators[self.name](obj, proposal)
elif hasattr(obj, "_%s_validate" % self.name):
meth_name = "_%s_validate" % self.name
cross_validate = getattr(obj, meth_name)
deprecated_method(
cross_validate,
obj.__class__,
meth_name,
"use @validate decorator instead.",
)
value = cross_validate(value, self)
return t.cast(G, value)
| (self, obj: Any, value: Any) -> Optional[~G] |
11,860 | traitlets.traitlets | _validate | null | def _validate(self, obj: t.Any, value: t.Any) -> G | None:
if value is None and self.allow_none:
return value
if hasattr(self, "validate"):
value = self.validate(obj, value)
if obj._cross_validation_lock is False:
value = self._cross_validate(obj, value)
return t.cast(G, value)
| (self, obj: Any, value: Any) -> Optional[~G] |
11,861 | traitlets.traitlets | class_init | Part of the initialization which may depend on the underlying
HasDescriptors class.
It is typically overloaded for specific types.
This method is called by :meth:`MetaHasDescriptors.__init__`
passing the class (`cls`) and `name` under which the descriptor
has been assigned.
| def class_init(self, cls: type[HasTraits], name: str | None) -> None:
"""Part of the initialization which may depend on the underlying
HasDescriptors class.
It is typically overloaded for specific types.
This method is called by :meth:`MetaHasDescriptors.__init__`
passing the class (`cls`) and `name` under which the descriptor
has been assigned.
"""
self.this_class = cls
self.name = name
| (self, cls: type[traitlets.traitlets.HasTraits], name: str | None) -> NoneType |
11,862 | traitlets.traitlets | default | The default generator for this trait
Notes
-----
This method is registered to HasTraits classes during ``class_init``
in the same way that dynamic defaults defined by ``@default`` are.
| def default(self, obj: t.Any = None) -> G | None:
"""The default generator for this trait
Notes
-----
This method is registered to HasTraits classes during ``class_init``
in the same way that dynamic defaults defined by ``@default`` are.
"""
if self.default_value is not Undefined:
return t.cast(G, self.default_value)
elif hasattr(self, "make_dynamic_default"):
return t.cast(G, self.make_dynamic_default())
else:
# Undefined will raise in TraitType.get
return t.cast(G, self.default_value)
| (self, obj: Optional[Any] = None) -> Optional[~G] |
11,863 | traitlets.traitlets | default_value_repr | null | def default_value_repr(self) -> str:
return repr(self.default_value)
| (self) -> str |
11,864 | traitlets.traitlets | error | Raise a TraitError
Parameters
----------
obj : HasTraits or None
The instance which owns the trait. If not
object is given, then an object agnostic
error will be raised.
value : any
The value that caused the error.
error : Exception (default: None)
An error that was raised by a child trait.
The arguments of this exception should be
of the form ``(value, info, *traits)``.
Where the ``value`` and ``info`` are the
problem value, and string describing the
expected value. The ``traits`` are a series
of :class:`TraitType` instances that are
"children" of this one (the first being
the deepest).
info : str (default: None)
A description of the expected value. By
default this is inferred from this trait's
``info`` method.
| def error(
self,
obj: HasTraits | None,
value: t.Any,
error: Exception | None = None,
info: str | None = None,
) -> t.NoReturn:
"""Raise a TraitError
Parameters
----------
obj : HasTraits or None
The instance which owns the trait. If not
object is given, then an object agnostic
error will be raised.
value : any
The value that caused the error.
error : Exception (default: None)
An error that was raised by a child trait.
The arguments of this exception should be
of the form ``(value, info, *traits)``.
Where the ``value`` and ``info`` are the
problem value, and string describing the
expected value. The ``traits`` are a series
of :class:`TraitType` instances that are
"children" of this one (the first being
the deepest).
info : str (default: None)
A description of the expected value. By
default this is inferred from this trait's
``info`` method.
"""
if error is not None:
# handle nested error
error.args += (self,)
if self.name is not None:
# this is the root trait that must format the final message
chain = " of ".join(describe("a", t) for t in error.args[2:])
if obj is not None:
error.args = (
"The '{}' trait of {} instance contains {} which "
"expected {}, not {}.".format(
self.name,
describe("an", obj),
chain,
error.args[1],
describe("the", error.args[0]),
),
)
else:
error.args = (
"The '{}' trait contains {} which " "expected {}, not {}.".format(
self.name,
chain,
error.args[1],
describe("the", error.args[0]),
),
)
raise error
# this trait caused an error
if self.name is None:
# this is not the root trait
raise TraitError(value, info or self.info(), self)
# this is the root trait
if obj is not None:
e = "The '{}' trait of {} instance expected {}, not {}.".format(
self.name,
class_of(obj),
info or self.info(),
describe("the", value),
)
else:
e = "The '{}' trait expected {}, not {}.".format(
self.name,
info or self.info(),
describe("the", value),
)
raise TraitError(e)
| (self, obj: traitlets.traitlets.HasTraits | None, value: Any, error: Optional[Exception] = None, info: Optional[str] = None) -> NoReturn |
11,865 | traitlets.traitlets | from_string | Get a value from a config string
such as an environment variable or CLI arguments.
Traits can override this method to define their own
parsing of config strings.
.. seealso:: item_from_string
.. versionadded:: 5.0
| def from_string(self, s: str) -> G | None:
"""Get a value from a config string
such as an environment variable or CLI arguments.
Traits can override this method to define their own
parsing of config strings.
.. seealso:: item_from_string
.. versionadded:: 5.0
"""
if self.allow_none and s == "None":
return None
return s # type:ignore[return-value]
| (self, s: str) -> Optional[~G] |
11,866 | traitlets.traitlets | get | null | def get(self, obj: HasTraits, cls: type[t.Any] | None = None) -> G | None:
assert self.name is not None
try:
value = obj._trait_values[self.name]
except KeyError:
# Check for a dynamic initializer.
default = obj.trait_defaults(self.name)
if default is Undefined:
warn(
"Explicit using of Undefined as the default value "
"is deprecated in traitlets 5.0, and may cause "
"exceptions in the future.",
DeprecationWarning,
stacklevel=2,
)
# Using a context manager has a large runtime overhead, so we
# write out the obj.cross_validation_lock call here.
_cross_validation_lock = obj._cross_validation_lock
try:
obj._cross_validation_lock = True
value = self._validate(obj, default)
finally:
obj._cross_validation_lock = _cross_validation_lock
obj._trait_values[self.name] = value
obj._notify_observers(
Bunch(
name=self.name,
value=value,
owner=obj,
type="default",
)
)
return t.cast(G, value)
except Exception as e:
# This should never be reached.
raise TraitError("Unexpected error in TraitType: default value not set properly") from e
else:
return t.cast(G, value)
| (self, obj: traitlets.traitlets.HasTraits, cls: Optional[type[Any]] = None) -> Optional[~G] |
11,867 | traitlets.traitlets | get_default_value | DEPRECATED: Retrieve the static default value for this trait.
Use self.default_value instead
| def get_default_value(self) -> G | None:
"""DEPRECATED: Retrieve the static default value for this trait.
Use self.default_value instead
"""
warn(
"get_default_value is deprecated in traitlets 4.0: use the .default_value attribute",
DeprecationWarning,
stacklevel=2,
)
return t.cast(G, self.default_value)
| (self) -> Optional[~G] |
11,868 | traitlets.traitlets | get_metadata | DEPRECATED: Get a metadata value.
Use .metadata[key] or .metadata.get(key, default) instead.
| def get_metadata(self, key: str, default: t.Any = None) -> t.Any:
"""DEPRECATED: Get a metadata value.
Use .metadata[key] or .metadata.get(key, default) instead.
"""
if key == "help":
msg = "use the instance .help string directly, like x.help"
else:
msg = "use the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)"
warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2)
return self.metadata.get(key, default)
| (self, key: str, default: Optional[Any] = None) -> Any |
11,869 | traitlets.traitlets | info | null | def info(self) -> str:
return self.info_text
| (self) -> str |
11,870 | traitlets.traitlets | init_default_value | DEPRECATED: Set the static default value for the trait type. | def init_default_value(self, obj: t.Any) -> G | None:
"""DEPRECATED: Set the static default value for the trait type."""
warn(
"init_default_value is deprecated in traitlets 4.0, and may be removed in the future",
DeprecationWarning,
stacklevel=2,
)
value = self._validate(obj, self.default_value)
obj._trait_values[self.name] = value
return value
| (self, obj: Any) -> Optional[~G] |
11,871 | traitlets.traitlets | instance_init | Part of the initialization which may depend on the underlying
HasDescriptors instance.
It is typically overloaded for specific types.
This method is called by :meth:`HasTraits.__new__` and in the
:meth:`BaseDescriptor.instance_init` method of descriptors holding
other descriptors.
| def instance_init(self, obj: t.Any) -> None:
"""Part of the initialization which may depend on the underlying
HasDescriptors instance.
It is typically overloaded for specific types.
This method is called by :meth:`HasTraits.__new__` and in the
:meth:`BaseDescriptor.instance_init` method of descriptors holding
other descriptors.
"""
| (self, obj: Any) -> NoneType |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.