Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning variable to private method

I have been working on a project that is using Google App Engine's python sdk. I was digging around in it and saw a lot of methods like this.

def _put(self, bla, bla):
    do something
put = _put

Is there any reason they assign the private variable like this? I mean I don't see the point of defining a method as private and then assigning it to a non private variable. Why not just make the method its self public?

def put(self, bla, bla):
    do something

The only then I can think of is it is done this way to meet some "proper coding style" rules. I mainly interested because I would like to get better at writing proper python code and wanted to know if this is something I should be doing myself?

EDIT: Thanks @falsetru for the link! Here is what I'm talking about (https://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/ext/ndb/model.py?r=410#3340)

like image 591
amiller2571 Avatar asked Feb 04 '14 14:02

amiller2571


2 Answers

Guido's explanation for this pattern in the NDB code:

NDB has a different rule for public vs. protected names. Many (but not all) of the names starting with an underscore are actually considered public APIs, because we don't want to reserve their method names as property names. We just alias the more user-friendly underscore-less names for convenience (e.g. the real method is _put(), and you should really use this, but we let you use put() as long as you don't have a property named 'put').

like image 167
Greg Avatar answered Sep 29 '22 09:09

Greg


Only one (a little) reasonable purpose of doing it is closure:

def wrapper():
    x = 2
    def _put(self, bla, bla):
       return x + 2

    self.put = _put
like image 43
IProblemFactory Avatar answered Sep 29 '22 10:09

IProblemFactory