1

I'm new to python, just have one question:

Python don't need to declare variable types. For example, when we use functions, we don't declare which type should be passed in. So sometimes, I can't figure out which type the passed in parameter actually is or do I pass in an invalid parameter.

For example, a parameter named: run_date, Its type can be string or datetime or date. I have to find it from the code...

Is there a way to solve this problem? I think I should do good naming. But howto?

I don't mean to check the type in the code. I just get confused with the function parameters when coding... I always forget which type the parameter is...

Lory_yang
  • 363
  • 5
  • 13
  • I guess the most important part is to good naming of the variables, that indicate the type. For details use [Docstrings](http://www.python.org/dev/peps/pep-0257/) - some Ide's/Editors display them and you can access this information in REPL EDIT: I thought you asked how to determine the correct type to pass to another function, and not to check if the passed in parameter is of the correct type – Bernhard Kircher Aug 30 '13 at 08:29

2 Answers2

2

Python uses what is called "Duck Typing" i.e. if it looks like a duck and it sounds like a duck you might as well call it a duck.

You can use:

  1. Parameter type checking,
  2. Parameter conversion,
  3. Exceptions &
  4. Documentation
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
1

Well ... welcome to the python world :).

You can define a function like this:

def value_type(x):
    # for type of dictionary
    if isinstance(x, dict):
        return list(set(x.values()))
    # for type of string including unicode 
    elif isinstance(x, str) or isinstance(x, unicode):
        mpla mpla...
    # for type of integer
    elif isinstance(x, int):
        mpla mpla...
    else:
        return None
Spyros Lalos
  • 86
  • 1
  • 2