In Python, the dir() function is used to display a list of attributes, classes, methods of the argument which is passed in to it, right ?
For example there is a module email in python
import email
dir(email)
Result:
['Charset', 'Encoders', 'Errors', 'FeedParser', 'Generator', 'Header', 'Iterators', 'LazyImporter', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Message', 'Parser', 'Utils', '_LOWERNAMES', '_MIMENAMES', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_name', 'base64MIME', 'email', 'importer', 'message_from_file', 'message_from_string', 'mime', 'quopriMIME', 'sys']
So what I want to know is how to tell whether a given object in the above list is an attribute, method, class, or function.
From the above list, we can expect that __all__, __builtins__, __doc__, etc. are attributes, but how can we differentiate all/remaining of these types just by looking at the list?
They’re all attributes, some of those attributes might reference functions, some classes, or objects. The ones like
__this__are commonly called magic methods.You can look at:
But the best answer is: “What do I care?”
Any information you need to know about the interface is better found in the documentation of the module. The types of various attributes are of little use, low importance (and
dircan be incomplete, too).So don’t bother type checking. It is worth knowing (and using) the python naming conventions though (see pep8):
CamelCasefor classessnake_casefor functions and methodsSHOUTY_CASEfor constants_leadingunderscores for ‘private’ things (i.e. undocumented, implementation detail, not intended to be part of public interface)__doubleleading underscores for enabling name mangling, it’s a way to handle possible namespace collisions in complex inheritance situations (a very obscure feature that you almost certainly don’t need in normal usage)__dunder__“double underscore” things for magic methods as mentioned previously, these are datamodel hooks for Python itself. You can redefine existing hooks to customize behaviour in your classes and modules, but don’t invent new magic names just for your own purposes, use normal attributes instead.