Reputation: 1
I'm trying to wrap the built-in function dir()
to sort its results. If I define and pass an argument to it, it works fine. However if I try to get it to show the root namespace, it won't work because it either requires an argument or gets an empty object which it returns attributes for instead.
I've tried redefining it with def dirs(*function):
argv instead, but that returns a list, not the current scope either.
Is there a way to wrap this built-in with the same functionality? I don't know C so the built-in source code wasn't much help to me, searching shows a lot of results for files in directories, but I can't seem to find how to crack this one.
def dirs(function):
print '{}'.format(type(function))
try:
for i in sorted(dir(function)):
print '{}'.format(i)
except:
for i in sorted(dir()):
print '{}'.format(i)
I've tried all of the data types I could think of, but I can't replicate the behaviour of the reference behaviour below.
print '# first for reference, a sorted dir()'
for i in sorted(dir()):
print '{}'.format(i)
print '# next up: double quoted string'
dirs("")
print '# next up: None'
dirs(None)
print '# next up: empty dictionary'
dirs({})
print '# next up: empty set'
dirs(())
print '# next up: empty list'
dirs([])
Here's a sample of the output, truncated for brevity.
# Result:
# first for reference, a sorted dir()
FnOpenPluginInstaller
__allcompletions
[...]
tools_dir
windowContext
# next up: double quoted string
<type 'str'>
__add__
__class__
[...]
upper
zfill
# next up: None
<type 'NoneType'>
__class__
__delattr__
[...]
__str__
__subclasshook__
# next up: empty dictionary
<type 'dict'>
__class__
__cmp__
[...]
viewkeys
viewvalues
# next up: empty set
<type 'tuple'>
__add__
__class__
[...]
count
index
# next up: empty list
<type 'list'>
__add__
__class__
[...]
reverse
sort
Upvotes: 0
Views: 60
Reputation: 263
How about something like this:
def dirs(function=None):
if function is None:
dirs_notsorted = dir()
else:
dirs_notsorted = dir(function)
for i in sorted(dirs_notsorted):
print('{}'.format(i))
print(dirs())
print(dirs([]))
Upvotes: 1