Skip to content

Commit dea66ea

Browse files
committed
Refactor the to_string function to make it more readable
1 parent 2e7339d commit dea66ea

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

pygmt/alias.py

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -84,27 +84,25 @@ def to_string(
8484
>>> to_string("invalid", mapping={"mean": "a", "mad": "d", "full": "g"})
8585
'invalid'
8686
"""
87-
# Return None if the value is None or False.
88-
if value is None or value is False:
87+
if value is None or value is False: # None and False are converted to None.
8988
return None
90-
# Return an empty string if the value is True. We don't have to check 'prefix' since
91-
# it defaults to an empty string!
92-
if value is True:
89+
if value is True: # True is converted to an empty string with the optional prefix.
9390
return f"{prefix}"
9491

95-
# Convert any value to a string or a sequence of strings.
96-
if is_nonstr_iter(value): # Is a sequence.
97-
value = [str(item) for item in value] # Convert to a sequence of strings
98-
if separator is None:
99-
# A sequence is given but separator is not specified. Return a sequence of
100-
# strings, to support repeated GMT options like '-B'. 'prefix' makes no
101-
# sense and is ignored.
102-
return value
103-
value = separator.join(value) # Join the sequence by the separator.
104-
elif mapping: # Mapping long-form arguments to short-form arguments.
105-
value = value[0] if mapping is True else mapping.get(value, value)
106-
# Return the final string with the optional prefix.
107-
return f"{prefix}{value}"
92+
# Convert a non-sequence value to a string.
93+
if not is_nonstr_iter(value):
94+
if mapping: # Mapping long-form arguments to short-form arguments.
95+
value = value[0] if mapping is True else mapping.get(value, value)
96+
return f"{prefix}{value}"
97+
98+
# Convert a sequence of values to a sequence of strings.
99+
# In some cases, "prefix" and "mapping" are ignored. We can enable them when needed.
100+
_values = [str(item) for item in value]
101+
if separator is None:
102+
# Sequence is given but separator is not specified. Return a sequence of strings
103+
# for repeatable GMT options like '-B'.
104+
return _values
105+
return f"{prefix}{separator.join(_values)}"
108106

109107

110108
@dataclasses.dataclass

0 commit comments

Comments
 (0)