Reputation: 12670
The following lambda returns empty ""
for filenames without a slash (e.g. "local.txt"
):
lambda filename: os.path.dirname(filename)
I would like to ensure (in very concise syntax) that the lambda always returns a proper directory name, i.e. "."
instead of ""
.
Is there more concise way for doing this than the following:
lambda filename: os.path.dirname(filename) if os.path.dirname(filename) != "" else "."
IMO it would be nice if os.path.dirname
would not have to be specified (perhaps even evaluated) twice. A conditional expression with one branch instead of two (if such a construct exists) could support come in handy.
Upvotes: 0
Views: 44
Reputation: 798814
Take advantage of or
's coalescing behavior:
lambda filename: os.path.dirname(filename) or "."
Upvotes: 1