Tip to filter results of a dir command

Pernelle Marone-Hitz
Pernelle Marone-Hitz Member, Moderator, Employee Posts: 871
100 Answers 500 Comments 250 Likes First Anniversary
✭✭✭✭
edited June 2023 in Structures

Tip to filter results of a dir command

Tagged:

Answers

  • Pernelle Marone-Hitz
    Pernelle Marone-Hitz Member, Moderator, Employee Posts: 871
    100 Answers 500 Comments 250 Likes First Anniversary
    ✭✭✭✭
    Answer ✓

    To check all available methods and properties of an object we often use the dir() command.

    For example, to check what's available for an object referenced by "connect", we'll use:

    dir(connect)

    If the returned list is long, it is very useful to filter it by some keywords that we're interested in. For this, the filter() method can be used. For example, to get all methods and properties that have a "Geometry" keyword in their name, use:

    filter(lambda x: ("Geometry" in x), dir(connect))

  • Vishnu
    Vishnu Member, Employee Posts: 222
    100 Comments 100 Likes Second Anniversary Name Dropper
    ✭✭✭✭
    Answer ✓

    I had created a button sometime back on this using what Pernelle mentioned above. Could be useful tool too.

    All you need to do is import the button in mechanical to use this.

    How to use:

    1. Click on an object in mechanical tree
    2. Click on this button
    3. Enter a keyword to search for methods and properties
    4. Returns list of all methods and properties available.

    Search button

    button link below:

    Button

  • James Derrick
    James Derrick Administrator, Employee Posts: 283
    Ancient Membership 100 Comments 100 Likes 25 Answers
    admin
    Answer ✓

    As an addendum to Pernelle's answer:

    In Python 3, rather than using filter and lambda it is more pythonic (and faster) to use a list comprehension. So,

    filter(lambda x: ("Geometry" in x), dir(connect))
    

    becomes

    filtered_list = [x for x in dir(connect) if "Geometry" in x]
    

    However in ACT and ironpython it is usually better to use map/filter/reduce and lambda, as explained here.

    This is because in Python 2 the list comprehension will overwrite the x variable if it is already in use, or will enter it into the namespace if it is not. In Python 3 this is not the case, and x remains a local variable inside the comprehension.