Matty
Matty

Reputation: 34513

Significance of double underscores in Python filename

Other than for __init__.py files, do the leading and trailing double underscores have any significance in a file name? For example, is __model__.py in any way more significant than model.py?

Upvotes: 5

Views: 3591

Answers (2)

Joseph Daniels
Joseph Daniels

Reputation: 31

Ahhh! I see you've discovered magic methods.

The double underscores are called "dunder" and they invoke special methods which can have some really neat effects on objects. They don't change significance, but they are pretty amazing voodoo, and a good tool to have on your belt.

Here's a link of many links, I learned all about magic methods through here. http://pythonconquerstheuniverse.wordpress.com/2012/03/09/pythons-magic-methods/

__init__ is a magic method for declaring stuff to happen on initialization of an object. It only preceded by __new__.

The most useful of these methods I've been using is the __dict__ method. The __dict__ method makes it so that all attributes in a class turn into key value pairs that can then be used like a dictionary. Although I don't think using it as a file name would be useful.

here's an example:

class Thing(object):
    def __init__(self): ##Init here is a magic method that determines what haps first
        self.tint = "black"
        self.color = "red"
        self.taste = "tangy"

thing = Thing()
dictionary_from_class = {}
for key in thing.__dict__.keys(): ##returns all key values. here: "tint, color, taste"
    dictionary_from_class[key] = thing.__dict__[key]

Fire up Idle in python, and try that out. Good luck in practicing python voodoo!

EDITED

Sorry, I really quickly read your question, let me mention this because I may have not covered it in my answer: If the filename is __init__.py, it does a similar thing, to what I mention before. It invokes the Initialization, and python will do that stuff as soon as the folder is reached for module usage. That is if you are reading off that file because it was called, such as referring to a folder of modules, and in that case you NEED a __init__.py file just to get python to recognize it inside the folder. You can use any of the magic methods as names to get a similar functionality upon usage.

I hope that clarification was useful.

-Joseph

Upvotes: -1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799082

Double underscores in filenames other than __init__.py and __main__.py have no significance to Python itself, but frameworks may use them to indicate/identify various things.

Upvotes: 8

Related Questions