Getting argument type in python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kaarthikeyapreyan
    New Member
    • Apr 2007
    • 106

    Getting argument type in python

    I want to get the type of arguments being passed to a method
    for eg.
    Code:
    def sample(num,string):
      print num
      print string
    
    sample(1,'hello')
    am expecting an output like :
    num -- type int
    string -- type string


    am able to retrieve it from isinstance method if i get arguments from sample(1,'hello '), but not with (num,string)
    which returns
    num -- type string
    string -- type string


    I can understand that these args are assigned with types only during their manipulations
    for e.g function sample will throw me a type error if i try to do
    num + string

    but when constructed using the PyObject they must have been definitely assigned with a data type like char or int
    how can i retrieve it if they are defined with PyObjects ?
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    You should be able to use the __class__ attribute (compare to literals' __class__ rather than trying to match the string) to do this.

    Eg:
    [CODE=python]
    def foo(bar):
    if bar.__class__ == [].__class__:
    #bar is a list
    pass
    elif bar.__class__ == 0.__class__:
    #bar is an int
    pass
    etc
    [/CODE]

    Comment

    • kaarthikeyapreyan
      New Member
      • Apr 2007
      • 106

      #3
      This is what i tried

      Code:
      >>> def hello(name,good):
      ...   sum=name+good
      ...   print name.__class__
      ...
      The __class__ returns the attribute of the class or the function defined
      Code:
      >>> hello.__class__
      <type 'function'>
      how do i get the attributes of the the arguments inside it cause
      Code:
      print name.__class__
      did not return anything

      Comment

      Working...