2

If I have a function that can operate on both sets and lists and should return a modified form of the sequence, is there a way to preserve the sequence type but still use a comprehension? For example, in the following if I call stripcommonpathprefix with a set, it works but has the undesired side effect of converting the set to a list. Is it possible to maintain the type (while still using a comprehension) without having to directly check isinstance and then return the correct type based on that? If not, what would be the cleanest way to do this?

def commonpathprefix(seq):

    return os.path.commonprefix(seq).rpartition(os.path.sep)[0] + os.path.sep


def stripcommonpathprefix(seq):

    prefix = commonpathprefix(seq)
    prefixlen = len(prefix)
    return prefix, [ p[prefixlen:] for p in seq ]

Thankyou and sorry if this is a basic question. I'm just starting to learn python.

P.S. I'm using Python 3.2.2

1
  • Why do you need to do this? I can't really think of any good reason... Commented Oct 16, 2011 at 20:55

2 Answers 2

5

There is no good way to preserve the type of the sequence. As you have guessed, if you really want to do this, you will have to convert the answer at the end to the type you want. It's quite likely that you don't need to do this, so you should think hard about it.

One shortcut that might help you if you do decide to convert: the types of the built-in sequences are also constructors that can create those sequences:

def strip_common_path_prefix(seq):
    # blah blah
    return prefix, type(seq)(result)
Sign up to request clarification or add additional context in comments.

Comments

0

There is no common way to do this without type checking. Also for sets you can use a set comprehension: { p[prefixlen:] for p in seq }.

2 Comments

It's been specified that Python 3 is the target, but just to remind anyone else who is looking at this, set comprehensions are Python 3 only. For Python 2, turn {...} into set(...). (Note that I don't mean the literal Ellipsis there; it's only valid in item access in Python 2's grammar, anyway;)
No, set comprehensions are available in Python 2.7+.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.