Question

I am new to Python, and have started working on code written by others.

In the source of packages downloaded from Pypi I have noticed the use of

import __module__

to use functions and classes defined in the src folder of packages.

Is this common practice? I actually can't really understand this kind of syntax, could you explain it to me or send me to some reference?

Was it helpful?

Solution

It's a python convention for some builtin objects. From PEP8:

__double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

But in the end it is not a "kind of syntax" to understand or not, __module__ is just a name with underscores in it. It's different from and completely unrelated to module.

An example to show you it's just a name:

>>> __foo__ = 42
>>> print foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined

>>> print _foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_foo' is not defined

>>> print __foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__foo' is not defined

>>> print __foo__
42

>>> type(__foo__)
<type 'int'>

Nothing inherently special about it.

Without more info about where you saw this though, it's hard to say what the author's intention was. Either they are importing some python builtins (e.g. from __future__ import...) or they are ignoring PEP8 and just named some objects in this style because they think it looks cool or more important.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top