-1

I'm using Python Python 3.10.8

I have a function that splits regex delimited strings into a tuple of arbitrary length. I want to count the number of sub-strings returned from my function. But when the source string does not have the delimiter, and my function correctly returns a tuple with a single string, the built-in len() returns the length of the string. How can I know/force that the return value is a single string, and not a collection of characters? This test function does not work as desired:

def test_da_tuple(subject_string, expected_length):
    da_tuple = MangleSplitter.tuple_of(subject_string)
    pprint.pprint(da_tuple)
    tuple_len = len(da_tuple)
    assert tuple_len == expected_length, ("\"%s\" split into %d not %d" % (subject_string, tuple_len, expected_length))

And some samples

MANGLED_STR_00 = "Jack L. Chalker - Demons of the Dancing GodsUC - #2DG"
CRAZYNESS = "A - B - C - D - F - F - G - H - I"
MANGLED_STR_07 = "Book Over"

I want my test_da_tuple() to verify 3 for MANGLED_STR_00, 9 for CRAZYNESS, and 1 for MANGLED_STR_07. Instead I get an assertion error that MANGLED_STR_07 split into 9 not 1.

Charlweed
  • 1,517
  • 2
  • 14
  • 22

1 Answers1

1

... my function correctly returns a tuple with a single string, the built-in len() returns the length of the string.

No, your function is not correctly adhering to its contract, to the promises it makes.

If your function returns t = ('foo', 'bar') then len(t) will report 2, good.

If your function returns a single string t = 'baz', that is completely different and the length is reported as 3. What you wanted instead was a 1-tuple: t = ('baz',)


Use print() debugging, or assert instanceof( ... , tuple), to verify it is returning a tuple rather than a str.

Write a Red unit test which highlights the current lossage you're complaining of, and then add a bug fix so the tests turns Green.


EDIT

is there a difference

Well, it certainly makes a difference how you choose to return the value. Here are three tuples. Some of them fit the function's contract.

>>> tuple(('foo', 'bar'))
('foo', 'bar')
>>> 
>>> tuple('abc')
('a', 'b', 'c')
>>> 
>>> tuple(('def',))
('def',)
>>> 
J_H
  • 17,926
  • 4
  • 24
  • 44
  • My function tries to force the return of a tuple. If there is no delimiter in the input it wraps the original string with tuple(input_string) and returns that. Should I return (input_string,) instead? is there a difference between tuple(input_string), (input_string,) and tuple(input_string,)? – Charlweed Feb 24 '23 at 01:38
  • `return (input_string,)` does what I expected `return tuple(input_string)` to do, and that's what I want. – Charlweed Feb 24 '23 at 18:01