madgui.util.misc module

Misc programming toolbox.

Functions

memoize(func)

Decorator for cached method that remembers its result from the first execution and returns this in all subsequent calls rather than executing the function again.

invalidate(obj, func)

Invalidate cache for memoized function.

cachedproperty(func)

Decorator for cached, writeable properties.

ranges(nums)

Identify groups of consecutive numbers in a list.

strip_suffix(s, suffix)

Strip a suffix from a string, if present.

relpath(path, start)

Try to make path relative to start using os.path.relpath, but returns path itself if this fails (e.g.

userpath(path)

Expand ‘~’ and environment variables in a user-given path string.

madgui.util.misc.cachedproperty(func)[source]

Decorator for cached, writeable properties.

>>> class Foo:
...     @cachedproperty
...     def bar(self):
...         return ['bar']
>>> foo = Foo()
>>> foo.bar
['bar']
>>> foo.bar is foo.bar
True
>>> foo.bar = 'qux'
>>> foo.bar
'qux'
>>> del foo.bar
>>> foo.bar
['bar']
madgui.util.misc.invalidate(obj, func)[source]

Invalidate cache for memoized function.

madgui.util.misc.memoize(func)[source]

Decorator for cached method that remembers its result from the first execution and returns this in all subsequent calls rather than executing the function again.

Example:

>>> class Foo:
...     @memoize
...     def bar(self):
...         print("executing bar…")
...         return 'bar'
>>> foo = Foo()
>>> foo.bar()
executing bar…
'bar'
>>> foo.bar()
'bar'

The cached result can be cleared using invalidate:

>>> invalidate(foo, 'bar')
>>> foo.bar()
executing bar…
'bar'

If arguments are passed, the result is always recomputed.

madgui.util.misc.ranges(nums)[source]

Identify groups of consecutive numbers in a list. Returns a list of intervals [start, end) as tuples.

madgui.util.misc.relpath(path, start)[source]

Try to make path relative to start using os.path.relpath, but returns path itself if this fails (e.g. if they are on different drives on windows).

madgui.util.misc.strip_suffix(s, suffix)[source]

Strip a suffix from a string, if present.

madgui.util.misc.userpath(path)[source]

Expand ‘~’ and environment variables in a user-given path string.