style question - hasattr

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ian

    style question - hasattr

    In old python code i would use 'has_key' to determine if an element
    was present in a dictionary.

    Python 3.0 will even removed 'has_key'. The reason for removal is that
    using the 'in' operator is a cleaner syntax and having two ways to
    achieve the same result is against the principle of the language.

    Ok, so what about 'hasattr' ??
    hasattr(myObjec t,'property')
    seems equivalent to
    'property' in dir(myObject)

    I would suggest that using the 'in' is cleaner in this case also. Is
    there a performance penalty here? Or is there reason why the two are
    not actually the same?

    Which style is preferred??
  • Terry Reedy

    #2
    Re: style question - hasattr


    "ian" <ian.team.pytho n@saltmob.comwr ote in message
    news:a59f2b47-d1c2-4db5-82a6-34746af5d1dc@w8 g2000prd.google groups.com...
    | In old python code i would use 'has_key' to determine if an element
    | was present in a dictionary.
    |
    | Python 3.0 will even removed 'has_key'. The reason for removal is that
    | using the 'in' operator is a cleaner syntax and having two ways to
    | achieve the same result is against the principle of the language.
    |
    | Ok, so what about 'hasattr' ??
    | hasattr(myObjec t,'property')
    | seems equivalent to
    | 'property' in dir(myObject)
    |
    | I would suggest that using the 'in' is cleaner in this case also. Is
    | there a performance penalty here?

    Yes, the construction of the dir.
    And I think there may be slight differences between the two.

    tjr



    Comment

    Working...