summaryrefslogtreecommitdiff
path: root/cmd2/utils.py
diff options
context:
space:
mode:
authoranselor <anselor@gmail.com>2018-05-02 15:29:45 -0400
committerGitHub <noreply@github.com>2018-05-02 15:29:45 -0400
commitd37004d05d0be67f48f35d6986ea899a35bcf89f (patch)
treeb4575eda772450b54620d16c09d4d29c52abdec7 /cmd2/utils.py
parent01e4e0296adf57c920c1e12c3c92f45f615894b1 (diff)
parenta95c8a065abeac286c196783393ecc49e4356f54 (diff)
downloadcmd2-git-d37004d05d0be67f48f35d6986ea899a35bcf89f.tar.gz
Merge pull request #379 from python-cmd2/pyscript
This merges pyscript and bash_completion branches into master
Diffstat (limited to 'cmd2/utils.py')
-rw-r--r--cmd2/utils.py45
1 files changed, 45 insertions, 0 deletions
diff --git a/cmd2/utils.py b/cmd2/utils.py
index 33215dc0..a975c6b8 100644
--- a/cmd2/utils.py
+++ b/cmd2/utils.py
@@ -2,8 +2,10 @@
# coding=utf-8
"""Shared utility functions"""
+import collections
from . import constants
+
def strip_ansi(text: str) -> str:
"""Strip ANSI escape codes from a string.
@@ -11,3 +13,46 @@ def strip_ansi(text: str) -> str:
:return: the same string with any ANSI escape codes removed
"""
return constants.ANSI_ESCAPE_RE.sub('', text)
+
+
+def strip_quotes(arg: str) -> str:
+ """ Strip outer quotes from a string.
+
+ Applies to both single and double quotes.
+
+ :param arg: string to strip outer quotes from
+ :return: same string with potentially outer quotes stripped
+ """
+ if len(arg) > 1 and arg[0] == arg[-1] and arg[0] in constants.QUOTES:
+ arg = arg[1:-1]
+ return arg
+
+
+def namedtuple_with_defaults(typename, field_names, default_values=()):
+ """
+ Convenience function for defining a namedtuple with default values
+
+ From: https://stackoverflow.com/questions/11351032/namedtuple-and-default-values-for-optional-keyword-arguments
+
+ Examples:
+ >>> Node = namedtuple_with_defaults('Node', 'val left right')
+ >>> Node()
+ Node(val=None, left=None, right=None)
+ >>> Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3])
+ >>> Node()
+ Node(val=1, left=2, right=3)
+ >>> Node = namedtuple_with_defaults('Node', 'val left right', {'right':7})
+ >>> Node()
+ Node(val=None, left=None, right=7)
+ >>> Node(4)
+ Node(val=4, left=None, right=7)
+ """
+ T = collections.namedtuple(typename, field_names)
+ T.__new__.__defaults__ = (None,) * len(T._fields)
+ if isinstance(default_values, collections.Mapping):
+ prototype = T(**default_values)
+ else:
+ prototype = T(*default_values)
+ T.__new__.__defaults__ = tuple(prototype)
+ return T
+