1

Here is a Pattern matching switch case in Scala, which basically matches different data types of the selector variable to the corresponding case variable and does some manipulation on it

def valueToString(x: Any): String = x match {

        case d: BigDecimal =>
          /* do something here */

        case a: Array[Byte] =>
          new String(a, "UTF-8")

        case s: Seq[_] =>
          /*do something here */

        case m: Map[_,_] =>
         /*do something here */

        case d: Date =>
          /*do something here */

        case t: Timestamp =>
          /*do something here */

        case r: Row =>
        /*do something here */
       }

Python does not have exactly support this kind of pattern matching. I know about switcher in Python, but it expects either regex or actual matching of the variable. How do i achieve the above functionality in Python

1
  • are d,a,s,m ... - regex constants? Commented Nov 14, 2015 at 7:31

1 Answer 1

1

Type checking

Use isinstance method to check the type of your generic input

import datetime

def value_to_string(input):

    # String
    if isinstance(input, basestring):
        return 'string'

    # BigDecimal
    if isinstance(input, int):
        return 'int'

    # Array
    if isinstance(input, list):
        return 'list'

    # Map
    if isinstance(input, dict):
        return 'dictionary'

    # Date
    if isinstance(input, datetime.date):
        return 'date'

    # ...

usage

print value_to_string('')
print value_to_string(1234)
print value_to_string([1,2,3])
print value_to_string({"id": 1})
print value_to_string(datetime.datetime.now())

output

string
int
list
dictionary
date
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! I will try this now. I should be able to include the manipulation of the input within these ifs instead of using a switch case right?
you may use the inside of these if statements

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.