For example, when traversing multiple levels up a hierarchy using dirname
I typically do this.
grandparent = os.path.dirname(__file__)
grandparent = os.path.dirname(grandparent)
Or, in case of more levels.
grandparent = = os.path.dirname(__file__)
for x in xrange(5):
grandparent = os.path.dirname(grandparent)
But I wonder if there's a less verbose method of doing this?
Such as
grandparent = y(5, os.path.dirname, __file__)
Where y
is the mysterious function I'm looking for.
And if not, what would such a function be called?
What about defining such higher order function yourself:
def repeat (f, x, n) :
for i in range(n):
x = f(x)
return x
With f
the function you wish to call, x
the first input in the sequence, and n
the number of times you wish to call this.
You can then call it for instance with:
>>> repeat(lambda x: x**2,2,3)
256
>>> repeat(os.path.dirname,'/home/kommusoft/testfolder/sqldump', 2)
'/home/kommusoft'
If you however plan to walk to the root of a directory, using a large number of repetitions is not safe: you never know that some user has made a cascade of over nine thousand directories.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With