traits.util Package

Utility functions, part of the Traits project.

traits.util.async_trait_wait Module

traits.util.async_trait_wait.wait_for_condition(condition, obj, trait, timeout=None)[source]

Wait until the given condition is true, re-evaluating on trait change.

This is intended for use in multithreading situations where traits can be modified from a different thread than the calling thread.

Wait until condition is satisfied. Raise a RuntimeError if condition is not satisfied within the given timeout.

condition is a callback function that will be called with obj as its single argument. It should return a boolean indicating whether the condition is satisfied or not.

timeout gives the maximum time in seconds to wait for the condition to become true. The default value of None indicates no timeout.

(obj, trait) give an object and trait to listen to for indication of a possible change: whenever the trait changes, the condition is re-evaluated. The condition will also be evaluated on entering this function.

Note that in cases of unusual timing it’s possible for the condition to be evaluated one more time after the wait_for_condition call has returned.

traits.util.camel_case Module

Defines utility functions for operating on camel case names.

class traits.util.camel_case.CamelCaseToPython[source]

Bases: object

Simple functor class to convert names from camel case to idiomatic Python variable names.

For example::
>>> camel2python = CamelCaseToPython
>>> camel2python('XMLActor2DToSGML')
'xml_actor2d_to_sgml'
traits.util.camel_case.camel_case_to_words(s)[source]

Convert a camel case string into words separated by spaces.

For example::
>>> camel_case_to_words('CamelCase')
'Camel Case'

traits.util.clean_strings Module

Provides functions that mange strings to avoid characters that would be problematic in certain situations.

traits.util.clean_strings.clean_filename(name, replace_empty='')[source]

Make a user-supplied string safe for filename use.

Returns an ASCII-encodable string based on the input string that’s safe for use as a component of a filename or URL. The returned value is a string containing only lowercase ASCII letters, digits, and the characters ‘-’ and ‘_’.

This does not give a faithful representation of the original string: different input strings can result in the same output string.

Deprecated since version 6.3.0: This function will be removed in a future version of Traits.

Parameters
  • name (str) – The string to be made safe.

  • replace_empty (str, optional) – The return value to be used in the event that the sanitised string ends up being empty. No validation is done on this input - it’s up to the user to ensure that the default is itself safe. The default is to return the empty string.

Returns

safe_string – A filename-safe version of string.

Return type

str

traits.util.clean_strings.clean_timestamp(dt=None, microseconds=False)[source]

Return a timestamp that has been cleansed of characters that might cause problems in filenames, namely colons. If no datetime object is provided, then uses the current time.

The timestamp is in ISO-8601 format with the following exceptions:

  • Colons ‘:’ are replaced by underscores ‘_’.

  • Microseconds are not displayed if the ‘microseconds’ parameter is

    False.

Deprecated since version 6.3.0: This function will be removed in a future version of Traits.

Parameters
  • dt (None or datetime.datetime) – If None, then the current time is used.

  • microseconds (bool) – Display microseconds or not.

Returns

Return type

A string timestamp.

traits.util.clean_strings.python_name(name)[source]

Attempt to make a valid Python identifier out of a name.

traits.util.deprecated Module

A decorator for marking methods/functions as deprecated.

traits.util.deprecated.deprecated(message)[source]

A factory for decorators for marking methods/functions as deprecated.

traits.util.home_directory Module

traits.util.home_directory.get_home_directory()[source]

Determine the user’s home directory.

traits.util.resource Module

Utility functions for managing and finding resources (e.g. images, files).

get_path : Returns the absolute path of a class or instance

create_unique_nameCreates a name with a given prefix that is not in a

given list of existing names. The separator between the prefix and the rest of the name can also be specified (default is a ‘_’)

find_resource: Given a setuptools project specification string

(‘MyProject>=2.1’) and a partial path leading from the projects base directory to the desired resource, will return either an opened file object or, if specified, a full path to the resource.

traits.util.resource.get_path(path)[source]

Returns an absolute path for the specified path.

‘path’ can be a string, class or instance.

traits.util.resource.create_unique_name(prefix, names, separator='_')[source]

Creates a name starting with ‘prefix’ that is not in ‘names’.

traits.util.resource.find_resource(project, resource_path, alt_path=None, return_path=False)[source]

Returns a file object or file path pointing to the desired resource.

This function will find a desired resource file and return an opened file object. The main method of finding the resource uses the pkg_resources resource_stream method, which searches your working set for the installed project specified and appends the resource_path given to the project path, leading it to the file. If setuptools is not installed or it cannot find/open the resource, find_resource will use the sys.path[0] to find the resource if alt_path is defined.

Deprecated since version 6.3.0.

Parameters
  • project (str) – The name of the project to look for the resource in. Can be the name or a requirement string. Ex: ‘MyProject’, ‘MyProject>1.0’, ‘MyProject==1.1’

  • resource_path (str) – The path to the file from inside the package. If the file desired is MyProject/data/image.jpg, resource_path would be ‘data/image.jpg’.

  • alt_path (str) – The path to the resource relative to the location of the application’s top-level script (the one with __main__). If this function is called in code/scripts/myscript.py and the resource is code/data/image.jpg, the alt_path would be ‘../data/image.jpg’. This path is only used if the resource cannot be found using setuptools.

  • return_path (bool) – Determines whether the function should return a file object or a full path to the resource.

Returns

file – A file object containing the resource. If return_path is True, ‘file’ will be the full path to the resource. If the file is not found or cannot be opened, None is returned.

Return type

file object or file path

traits.util.resource.store_resource(project, resource_path, filename)[source]

Store the content of a resource, given by the name of the project and the path (relative to the root of the project), into a newly created file.

The first two arguments (project and resource_path) are the same as for the function find_resource in this module. The third argument (filename) is the name of the file which will be created, or overwritten if it already exists. The return value in always None.

Deprecated since version 6.3.0.

traits.util.import_symbol Module

A function to import symbols.

traits.util.import_symbol.import_symbol(symbol_path)[source]

Import the symbol defined by the specified symbol path.

Examples

import_symbol(‘tarfile:TarFile’) -> TarFile import_symbol(‘tarfile:TarFile.open’) -> TarFile.open

To allow compatibility with old-school traits symbol names we also allow all-dotted paths, but in this case you can only import top-level names from the module.

import_symbol(‘tarfile.TarFile’) -> TarFile

traits.util.toposort Module

A simple topological sort on a dictionary graph.

exception traits.util.toposort.CyclicGraph[source]

Bases: Exception

Exception for cyclic graphs.

traits.util.toposort.topological_sort(graph)[source]

Returns the nodes in the graph in topological order.

traits.util.trait_documenter Module

A Trait Documenter (Subclassed from the autodoc ClassLevelDocumenter)

class traits.util.trait_documenter.TraitDocumenter(directive: DocumenterBridge, name: str, indent: str = '')[source]

Bases: sphinx.ext.autodoc.ClassLevelDocumenter

Specialized Documenter subclass for trait attributes.

The class defines a new documenter that recovers the trait definition signature of module level and class level traits.

To use the documenter, append the module path in the extension attribute of the conf.py.

objtype = 'traitattribute'

name by which the directive is called (auto…) and the default generated directive name

directivetype = 'attribute'
member_order = 60

order if autodoc_member_order is set to ‘groupwise’

priority = 12

priority if multiple documenters return True from can_document_member

classmethod can_document_member(member, membername, isattr, parent)[source]

Check that the documented member is a trait instance.

document_members(all_members=False)[source]

Trait attributes have no members

import_object()[source]

Get the Trait object.

Notes

Code adapted from autodoc.Documenter.import_object.

add_directive_header(sig)[source]

Add the directive header ‘attribute’ with the annotation option set to the trait definition.

traits.util.trait_documenter.trait_definition(*, cls, trait_name)[source]

Retrieve the portion of the source defining a Trait attribute.

For example, given a class:

class MyModel(HasStrictTraits)
    foo = List(Int, [1, 2, 3])

trait_definition(cls=MyModel, trait_name="foo") returns "List(Int, [1, 2, 3])".

Parameters
  • cls (MetaHasTraits) – Class being documented.

  • trait_name (str) – Name of the trait being documented.

Returns

The portion of the source containing the trait definition. For example, for a class trait defined as "my_trait = Float(3.5)", the returned string will contain "Float(3.5)".

Return type

str

Raises

ValueError – If trait_name doesn’t appear as a class-level variable in the source.

traits.util.trait_documenter.setup(app)[source]

Add the TraitDocumenter in the current sphinx autodoc instance.

traits.util.event_tracer Module

Record trait change events in single and multi-threaded environments.

class traits.util.event_tracer.SentinelRecord[source]

Sentinel record to separate groups of chained change event dispatches.

class traits.util.event_tracer.ChangeMessageRecord(time, indent, name, old, new, class_name)[source]

Message record for a change event dispatch.

time

Time stamp in UTC.

indent

Depth level in a chain of trait change dispatches.

name

The name of the trait that changed

old

The old value.

new

The new value.

class_name

The name of the class that the trait change took place.

class traits.util.event_tracer.CallingMessageRecord(time, indent, handler, source)[source]

Message record for a change handler call.

time

Time stamp in UTC.

indent

Depth level of the call in a chain of trait change dispatches.

handler

The traits change handler that is called.

source

The source file where the handler was defined.

class traits.util.event_tracer.ExitMessageRecord(time, indent, handler, exception)[source]

Message record for returning from a change event dispatch.

time

Time stamp in UTC.

indent

Depth level of the exit in a chain of trait change dispatch.

handler

The traits change handler that is called.

exception

The exception type (if one took place)

class traits.util.event_tracer.RecordContainer[source]

A simple record container.

This class is commonly used to hold records from a single thread.

record(record)[source]

Add the record into the container.

save_to_file(filename)[source]

Save the records into a file.

class traits.util.event_tracer.MultiThreadRecordContainer[source]

A container of record containers that are used by separate threads.

Each record container is mapped to a thread name id. When a RecordContainer does not exist for a specific thread a new empty RecordContainer will be created on request.

get_change_event_collector(thread_name)[source]

Return the dedicated RecordContainer for the thread.

If no RecordContainer is found for thread_name then a new RecordContainer is created.

save_to_directory(directory_name)[source]

Save records files into the directory.

Each RecordContainer will dump its records on a separate file named <thread_name>.trace.

class traits.util.event_tracer.ChangeEventRecorder(container)[source]

A single thread trait change event recorder.

Parameters

container (MultiThreadRecordContainer) – A container to store the records for each trait change.

container

A container to store the records for each trait change.

Type

MultiThreadRecordContainer

indent

Indentation level when reporting chained events.

Type

int

pre_tracer(obj, name, old, new, handler)[source]

Record a string representation of the trait change dispatch

post_tracer(obj, name, old, new, handler, exception=None)[source]

Record a string representation of the trait change return

class traits.util.event_tracer.MultiThreadChangeEventRecorder(container)[source]

A thread aware trait change recorder.

The class manages multiple ChangeEventRecorders which record trait change events for each thread in a separate file.

Parameters

container (MultiThreadChangeEventRecorder) – The container of RecordContainers to keep the trait change records for each thread.

container

The container of RecordContainers to keep the trait change records for each thread.

Type

MultiThreadChangeEventRecorder

tracers

Mapping from threads to ChangeEventRecorder instances.

Type

dict

close()[source]

Close and stop all logging.

pre_tracer(obj, name, old, new, handler)[source]

The traits pre event tracer.

This method should be set as the global pre event tracer for traits.

post_tracer(obj, name, old, new, handler, exception=None)[source]

The traits post event tracer.

This method should be set as the global post event tracer for traits.

traits.util.event_tracer.record_events()[source]

Multi-threaded trait change event tracer.

Example

This will install a tracer that will record all events that occur from setting of some_trait on the my_model instance:

>>> from trace_recorder import record_events
>>> with record_events() as change_event_container:
...     my_model.some_trait = True
>>> change_event_container.save_to_directory('C:\dev\trace')

The results will be stored in one file per running thread in the directory ‘C:devtrace’. The files are named after the thread being traced.