473,698 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Coding Style: Defining Functions within Methods?

I have been defining new class methods when I'm trying to simplify
some code. But I'm thinking I should just define functions within
that method because they aren't useful from the outside anyway.
Example:
Before:

class Mess(object):
def complicated(sel f, count):
for i in count:
self.do_loop(i)
def do_loop(self, i):
...whatever...
After:

class Cleaner(object) :
def complicated(sel f, count):
def do_loop(i)
...whatever...
for i in count:
do_loop(i)

The point is that do_loop is now not ``contaminating '' things. I
suppose do_loop could be __do_loop, but it would still show up in
places where I don't think it should (such as dir(Mess)).

Thoughts?

Thanks!
Harry.
Jul 18 '05 #1
7 3046
JCM
Generally I also find it cleanest to push functions down into the most
nested scope possible; it makes it clear that these are helper
functions and not meant to be called externally.

Harry Pehkonen <ha************ @hotpop.com> wrote:
I have been defining new class methods when I'm trying to simplify
some code. But I'm thinking I should just define functions within
that method because they aren't useful from the outside anyway.
Example:
Before: class Mess(object):
def complicated(sel f, count):
for i in count:
self.do_loop(i)
def do_loop(self, i):
...whatever...
After: class Cleaner(object) :
def complicated(sel f, count):
def do_loop(i)
...whatever...
for i in count:
do_loop(i) The point is that do_loop is now not ``contaminating '' things. I
suppose do_loop could be __do_loop, but it would still show up in
places where I don't think it should (such as dir(Mess)). Thoughts? Thanks!
Harry.

Jul 18 '05 #2
max
JCM wrote:
Generally I also find it cleanest to push functions down into the most
nested scope possible; it makes it clear that these are helper
functions and not meant to be called externally.

I love this style and really miss it in other languages...
my 2c.

Jul 18 '05 #3
ha************@ hotpop.com (Harry Pehkonen) writes:
I have been defining new class methods when I'm trying to simplify
some code. But I'm thinking I should just define functions within
that method because they aren't useful from the outside anyway.
Example:
Before: class Mess(object):
def complicated(sel f, count):
for i in count:
self.do_loop(i)
def do_loop(self, i):
...whatever...
After: class Cleaner(object) :
def complicated(sel f, count):
def do_loop(i)
...whatever...
for i in count:
do_loop(i) The point is that do_loop is now not ``contaminating '' things. I
suppose do_loop could be __do_loop, but it would still show up in
places where I don't think it should (such as dir(Mess)). Thoughts?


Definitely useful, especially as the inner function can see the same variables
as the outer (though I do keep getting bitten when I expect to be able update
variables).

Eddie
Jul 18 '05 #4
On 5 Sep 2003 09:37:05 -0700, ha************@ hotpop.com (Harry Pehkonen) wrote:
I have been defining new class methods when I'm trying to simplify
some code. But I'm thinking I should just define functions within
that method because they aren't useful from the outside anyway.
Example:
Before:

class Mess(object):
def complicated(sel f, count):
for i in count:
self.do_loop(i)
def do_loop(self, i):
...whatever...
After:

class Cleaner(object) :
def complicated(sel f, count):
def do_loop(i)
...whatever...
for i in count:
do_loop(i)

The point is that do_loop is now not ``contaminating '' things. I
suppose do_loop could be __do_loop, but it would still show up in
places where I don't think it should (such as dir(Mess)).

Thoughts?


I like defining nested functions except for the fact that a definition is executable code
in itself, and will be re-executed each time the outer function or method is called. I'm
not sure how long MAKE_FUNCTION or MAKE_CLOSURE take to execute, but IWT it must mean allocating
and glueing together the dynamic elements necessary for a distinct function/closure instance,
and then disposing of them at some point on/after their going out of scope, vs. e.g. just locating
a sibling method.

OTOH, the outer overhead may become relatively insignificant if the inner is called boocoo times
in a loop and/or recursively.

On the third hand, clear code will outweigh any performance issues for much code.

Regards,
Bengt Richter
Jul 18 '05 #5
ha************@ hotpop.com (Harry Pehkonen) wrote:
I have been defining new class methods when I'm trying to simplify
some code. But I'm thinking I should just define functions within
that method because they aren't useful from the outside anyway.


It's also possible to generate classes by using a factory function.
For an example of it getting a bit out of control see the code below.

Anton

---

from __future__ import division
from Tkinter import *

def template(x=None ):
class T(tuple):
def __new__(cls, *args):
return tuple.__new__(c ls, args)
def geta(self): return self[0]
def getb(self): return self[1]
a,b = map(property,[geta,getb])
return T

Point = template()
Rect = template(Point)
Cube = template(Rect)

class Transformer(Cub e):

def __init__(self, *args):
a,b = self.a,self.b
fx = (b.b.a-b.a.a)/(a.b.a-a.a.a)
fy = (b.b.b-b.a.b)/(a.b.b-a.a.b)
f = min(fx,fy)
wxc = (a.a.a+a.b.a)/2
wyc = (a.a.b+a.b.b)/2
vxc = (b.a.a+b.b.a)/2
vyc = (b.a.b+b.b.b)/2
xc = vxc-f*wxc
yc = vyc-f*wyc
self.f,self.xc, self.yc = f,xc,yc

def transform(self, R):
f,xc,yc = self.f,self.xc, self.yc
p1 = Point(f*R.a.a+x c, f*R.a.b+yc)
p2 = Point(f*R.b.a+x c, f*R.b.b+yc)
return Rect(p1,p2)

class Cartesian:

def __init__(self, master):
self.canvas = Canvas(master,w idth=500,height =500)
self.canvas.pac k(fill= BOTH, expand=YES)
master.bind("<E scape>", lambda event='ignored' ,
m=master: m.destroy())
master.bind("<C onfigure>", self.configure)

def configure(self, event):
self.draw()

def draw(self):
c = self.canvas
c.delete('all')
T = Transformer(sel f.b,self.a)
colors ='Red Green Blue Magenta Cyan Yellow'.split()
for i in range(50,0,-1):
R = Rect(Point(-i,-i),Point(i,i))
c.create_rectan gle(T.transform (R),
fill=colors[(i-1)%len(colors)])

def geta(self):
c = self.canvas
p1 = Point(0,0)
p2 = Point(c.winfo_w idth(), c.winfo_height( ))
return Rect(p1,p2)

def getb(self):
a = 50
p1 = Point(-a,-a)
p2 = Point(a,a)
return Rect(p1,p2)

a,b = map(property,[geta,getb])

def main():
root = Tk()
ca = Cartesian(root)
root.mainloop()

if __name__=='__ma in__':
main()

Jul 18 '05 #6
JCM
Bengt Richter <bo**@oz.net> wrote:
I like defining nested functions except for the fact that a definition is executable code
in itself, and will be re-executed each time the outer function or method is called. I'm
not sure how long MAKE_FUNCTION or MAKE_CLOSURE take to execute, but IWT it must mean allocating
and glueing together the dynamic elements necessary for a distinct function/closure instance,
and then disposing of them at some point on/after their going out of scope, vs. e.g. just locating
a sibling method.


This doesn't need to be slow--it's up to the implementation to try
to be as smart as possible. A compiler can do lambda-lifting to
transform a program with nested functions to one without, so there
really is nothing inherently slow about nested functions.
Jul 18 '05 #7
On Sun, 7 Sep 2003 08:11:15 +0000 (UTC), JCM <jo************ ******@myway.co m> wrote:
Bengt Richter <bo**@oz.net> wrote:
I like defining nested functions except for the fact that a definition is executable code
in itself, and will be re-executed each time the outer function or method is called. I'm
not sure how long MAKE_FUNCTION or MAKE_CLOSURE take to execute, but IWT it must mean allocating
and glueing together the dynamic elements necessary for a distinct function/closure instance,
and then disposing of them at some point on/after their going out of scope, vs. e.g. just locating
a sibling method.


This doesn't need to be slow--it's up to the implementation to try
to be as smart as possible. A compiler can do lambda-lifting to
transform a program with nested functions to one without, so there
really is nothing inherently slow about nested functions.

Agreed, but python is very dynamic, so "as smart as possible" may cost
more overall than calculatedly "dumb" in many cases. As it stands, the way
you code it will be pretty much the way it happens, so there will be some cost
to nesting functions. I just don't know how much without timing it. ... resisting ...
temptation ...

Succeeded, for now ;-)

Regards,
Bengt Richter
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1380
by: Joe Kelsey | last post by:
When defining public methods, which style do you prefer: style 1: function myObject (...) { this.member = 0; } myObject.prototype.method = function ()
1
3848
by: jarit | last post by:
Hi, Found these coding guidelines for C#, HTML, Javascript, Java, HTML, PL/SQL, T-SQL, VB and VBScript. Well written and free to download. www.demachina.com/products/swat Jeroen
144
6860
by: Natt Serrasalmus | last post by:
After years of operating without any coding standards whatsoever, the company that I recently started working for has decided that it might be a good idea to have some. I'm involved in this initiative. Typically I find that coding standards are written by some guy in the company who has a way of coding that he likes and then tries to force everybody else to write code the way he likes it, not for any rational reason, but simply for the...
39
3491
by: Patrick | last post by:
The c# code style guide that I follow suggests that class variables (fields) be coded with camel casing, like this: int recordId; string name; It also suggests that variables within methods and method parameters use camel casing, like this: void SetName(int id, string newName)
4
1507
by: Mike Labosh | last post by:
I realize that you people have not seen much of me other than some framework responses I have posted. I am primarily a VB guy (yes, you can laugh) But I have lurked here for several years, picking up little crumbs of C# wisdom. Perhaps it's just my style, but what's this annoying behavior of the IDE and how do I stop it: C# seems to want me to write all my code like this:
78
4897
by: Robert Baer | last post by:
The homepage i have had up and seemingly working is: http://oil4lessllc.com/ However, the validator has so many complaints, and being so incompetent, i have no clue as to how to fix it all. Would the use of Dreamweaver be of great help?
19
3966
by: auratius | last post by:
http://www.auratius.co.za/CSharpCodingStandards.html Complete CSharp Coding Standards 1. Naming Conventions and Styles 2. Coding Practices 3. Project Settings and Project Structure 4. Framework-Specific Guidelines Naming Conventions and Styles
17
2468
by: Jason Doucette | last post by:
I am converting a C-style unit into a C++ class. I have an implementation function that was defined in the .cpp file (so it was hidden from the interface that exists in the .h file). It uses a structure that is only needed by the implementation, so it were declared in the .cpp file, as well. Now, when converting this into a class, the class definition exists in the .h file, since it's required by the interface. The implementation...
13
2491
by: stephenpas | last post by:
We are trying to monkey-patch a third-party library that mixes new and old-style classes with multiple inheritance. In so doing we have uncovered some unexpected behaviour: <quote> class Foo: pass class Bar(object): pass
0
8676
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8608
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8897
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8867
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6522
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2332
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2006
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.