3

When I import a module, such as sys, I am assuming that I am importing a script, and in order to access its functions, I have to use the dot notation. For example, I want to write something out to the console:

    sys.stderr.write("Error")

Here, I access the stderr "function?" from the module sys, but then I access its write attribute which is also a function? How do I know if stderr is a class that is subclassing sys, or if it is a function?

Thanks a lot.

2
  • If you open the Python interpreter, import sys and type sys.stderr it outputs <_io.TextIOWrapper name='<stderr>' mode='w' encoding='cp437'>, telling you that sts.stderr is a _io.TextIOWrapper object. Doing that same for sys.stderr.write gives you <built-in method write of _io.TextIOWrapper object at 0x00B18830> (This is for Python 3.5.0) Commented Jul 19, 2017 at 0:46
  • "How do I know if stderr is a class that is subclassing sys" It sounds like you are not using the term "subclassing" correctly. "Subclassing" means that a class inherits from another class, not that it is in a module's namespace. Commented Jul 19, 2017 at 1:18

2 Answers 2

3

Once you import a module (like sys or anything), the dot-notation may then refer to anything it contains. You could also import a 'package' contains modules, classes, methods in classes, functions in modules, etc.

>>> import sys
>>> type(sys)
<class 'module'>
>>> sys.stderr
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='cp437'>
>>> type(sys.stderr)
<class '_io.TextIOWrapper'>
>>> type(sys.stderr.write)
<class 'builtin_function_or_method'>
>>>

It's meant to be generic sort-of-attribute access where each thing inside another is accessed via the dot, as if it was an attribute of that object, which it is.

I believe it's meant to be ambiguous so that the user of a module/package does not need to be concerned with the implementation details of those objects. And if they change, as long as the structure and names are maintained, the actual object it refers to is not of concern to the user. They could always use type() or help() to look at the details or use other introspection tools.

0
0

The dot is a generic element reference, not merely a function. This says to get the stderr element of sys, then get the write element of stderr. For this to work, stderr must be an object that contains elements, and write must be a callable element ... since the parentheses mean that we're trying to call write.

We do have to know the general semantic of each element: which are packages, which are constants, which are functions, etc.

1
  • 1
    note that "write" can be any callable, not necessarily a function
    – Shreyans
    Commented Jan 21 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.