util Package

util Package

Utility functions, part of the Traits project.

Copyright:2003-2013 Enthought, Inc.

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.

camel_case Module

Defines utility functions for operating on camel case names.

class traits.util.camel_case.CamelCaseToPython[source]

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'

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)[source]

Munge a string to avoid characters that might be problematic as a filename in some filesystems.

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.

Description

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.
Parameters:
  • dt (None or datetime.datetime) – If None, then the current time is used.
  • microseconds (bool) – Display microseconds or not.
Returns:

A string timestamp.

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

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

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.

home_directory Module

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

Determine the user’s home directory.

resource Module

Utility functions for managing and finding resources (ie. images/files etc).

get_path : Returns the absolute path of a class or instance

create_unique_name
: Creates 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.

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 (file object or file path) – 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.

Description

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.

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.

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

toposort Module

A simple topological sort on a dictionary graph.

exception traits.util.toposort.CyclicGraph[source]

Bases: exceptions.Exception

Exception for cyclic graphs.

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

Returns the nodes in the graph in topological order.

trait_documenter Module

A Trait Documenter (Subclassed from the autodoc ClassLevelDocumenter)

copyright:Copyright 2012 by Enthought, Inc
class traits.util.trait_documenter.TraitDocumenter(directive, name, indent=u'')[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.

Warning

Using the TraitDocumenter in conjunction with TraitsDoc is not advised.

objtype = 'traitattribute'
directivetype = 'attribute'
member_order = 60
priority = 12
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

add_content(more_content, no_docstring=False)[source]

Never try to get a docstring from the trait.

import_object()[source]

Get the Trait object.

Note

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.setup(app)[source]

Add the TraitDocumenter in the current sphinx autodoc instance.

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.

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.

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(*args, **kwds)[source]

Multi-threaded trait change event tracer.

Usage

>>> 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')

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

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.