Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
which is "better"?
#2
The attributes are callables and not properties.
In your example you are not calling the functions.

This example checks everything.

def pathftn(path):
    mapping = collections.OrderedDict([
        ('is_symlink', 'l'),
        ('is_block_device', 'b'),
        ('is_char_device', 'c'),
        ('is_dir', 'd'),
        ('is_file', 'f'),
        ('is_socket', 's'),
        ('is_fifo', 'p'),
    ])
    return ''.join(
        value if getattr(path, func)() else '_'
        for func, value in mapping.items()
        )
Same function which does the same like yours:

def pathftn(path, unknown='?'):
    mapping = collections.OrderedDict([
        ('is_symlink', 'l'),
        ('is_block_device', 'b'),
        ('is_char_device', 'c'),
        ('is_dir', 'd'),
        ('is_file', 'f'),
        ('is_socket', 's'),
        ('is_fifo', 'p'),
    ])
    for func, value in mapping.items():
        if getattr(path, func)():
            return value
    else:
        return unknown
The mapping can be outside of the function.

So when you see constructs like:

if foo: x=10
elif bar: x=20
elif baz: x=30
else: x=-1
You better use a switch statement like in C.
But Python doesn't have this construct.
Pythonists using as replacement a mapping.
The keys and values of a dict can also be callables (functions or methods).
The benefit is, that you have as first your data structure and afterwards
the code, which is executing the logic. Logic is spitted from data.

To preserve the Order, I use collections.OrderedDict.
In Python 3.7 they guarantee preserving the order in dicts as a
language feature and no longer as implementation detail.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
which is "better"? - by Skaperen - Mar-31-2018, 12:34 AM
RE: which is "better"? - by DeaD_EyE - Mar-31-2018, 10:36 AM
RE: which is "better"? - by wavic - Mar-31-2018, 02:26 PM
RE: which is "better"? - by Budsy - Mar-31-2018, 06:26 PM
RE: which is "better"? - by Gribouillis - Apr-01-2018, 07:08 AM
RE: which is "better"? - by Skaperen - Apr-02-2018, 04:29 AM
RE: which is "better"? - by ljmetzger - Apr-02-2018, 09:45 AM
RE: which is "better"? - by Gribouillis - Apr-02-2018, 10:10 AM
RE: which is "better"? - by Skaperen - Apr-03-2018, 02:47 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020