473,783 Members | 2,563 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Listing functions in a file IN ORDER

I have a python file with a number of functions named with the form doX so :

doTask1
doThing
doOther

The order these are executed in is important and I want them to be executed top-down. They all have the same parameter signature so I'd like to do :

for name, func in vars(mymodule). items():
if not name.startswith ("do") and callable(func):
apply(func,my_p arams)

but the problem is that the return from vars is not ordered the same as in the file. i.e. it could be

doOther
doTask1
doThing

The low tech solution is to use dir() and re-name the functions to sort alphabetically but perhaps there is a more elegant solution?

Jul 18 '05 #1
6 1919
Ian Sparks wrote:
I have a python file with a number of functions named with the form doX so :

doTask1
doThing
doOther

The order these are executed in is important and I want them to be executed top-down. They all have the same parameter signature so I'd like to do :

for name, func in vars(mymodule). items():
if not name.startswith ("do") and callable(func):
apply(func,my_p arams)

but the problem is that the return from vars is not ordered the same as in the file. i.e. it could be


Just add a list which sums up the function names in the order you want:

functions = ["doTask1", "doThing", "doOther".. ....]

and iterate over that list?

--Irmen
Jul 18 '05 #2
Ian Sparks wrote:
I have a python file with a number of functions named with the form doX so
:

doTask1
doThing
doOther

The order these are executed in is important and I want them to be
executed top-down. They all have the same parameter signature so I'd like
to do :

for name, func in vars(mymodule). items():
if not name.startswith ("do") and callable(func):
apply(func,my_p arams)

but the problem is that the return from vars is not ordered the same as in
the file. i.e. it could be

doOther
doTask1
doThing

The low tech solution is to use dir() and re-name the functions to sort
alphabetically but perhaps there is a more elegant solution?


The following minimal code will break with methods and nested functions.

<xyz.py>
def z(): print "ZZZ"
def y(): print "YYY"
def x(): print "XXX"
</xyz.py>

<runxyz.py>
import compiler

class Visitor:
def __init__(self, module, *args):
self.module = module
self.args = args
def visitFunction(s elf, node):
getattr(self.mo dule, node.name)(*sel f.args)

def callInOrder(mod ule, *args):
ast = compiler.parseF ile(module.__fi le__)
compiler.walk(a st, Visitor(module, *args))

if __name__ == "__main__":
import xyz
callInOrder(xyz )
</runxyz.py>

Not particularly elegant, but crazy enough to be worth posting...

Peter

Jul 18 '05 #3
On Tue, 29 Jun 2004, Irmen de Jong wrote:
Ian Sparks wrote:

Just add a list which sums up the function names in the order you want:

functions = ["doTask1", "doThing", "doOther".. ....]

and iterate over that list?


Better yet, just have a list of the functions themselves:

functions = [doTask1, doThing, doOther]

for function in functions:
function(*args)

Note the use of function(*args) instead of apply(function, args). apply()
is deprecated starting with Python 2.3 in favor of this 'extended call
syntax'.

Jul 18 '05 #4
In article <ma************ *************** ***********@pyt hon.org>,
Ian Sparks <Ia********@etr ials.com> wrote:
I have a python file with a number of functions named with the form doX so :

doTask1
doThing
doOther

The order these are executed in is important and I want them to be
executed top-down. They all have the same parameter signature so I'd
like to do :


All you need to do is sort them by line number:

from types import FunctionType

def linecompare(a,b ):
return cmp(a.func_code .co_firstlineno , b.func_code.co_ firstlineno)

func_list = [ f for (n,f) in vars(mymodule). items()
if isinstance(f, FunctionType) and n.startswith("d o") ]

func_list.sort( linecompare)
Notice that I looked just for functions since other callables like
classes don't have the right attributes.

Cheers,

Duncan.

--
-- Duncan Grisby --
-- du****@grisby.o rg --
-- http://www.grisby.org --
Jul 18 '05 #5
Ian Sparks wrote:
I have a python file with a number of functions named with the form doX so :

doTask1
doThing
doOther

The order these are executed in is important and I want them to be executed top-down.


IMHO making the order in which the functions are defined in a module
define the order in which they will be called upon in another program
seems to be an awkward solution.

You are encoding program logic into layout information thus
solving the problem of 'forgetting about a function' by creating
a more devious one.

Istvan.


Jul 18 '05 #6
Istvan Albert wrote:
Ian Sparks wrote:
...python file with functions named doXXX ... order executed important...
I want the system to do code discovery because I'm too dumb to
remember to put things in the list.


IMHO making the order in which the functions are defined in a module
define the order in which they will be called upon in another program
seems to be an awkward solution.

I agree. Separate the two concerns:

import sets
chosen = sets.Set(module .function_list)
actuals = sets.Set([function for name, function in vars(module)
if name.startswith ('do') and callable(functi on))])
for function in actuals - chosen:
print >>stderr, 'Warning! forgot about', function.__name __
# now call them in the specified order.
for function in function_list:
function(*args)

--
-Scott David Daniels
Sc***********@A cm.Org
Jul 18 '05 #7

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

Similar topics

15
2528
by: Kim Jensen | last post by:
I'd like to make a directory listing where instead of the entire filename I need it to show the filename minus the extention and get the value of charname= in the file itself. I've been told that I had to turn the directory listing into an array and then use "foreach (array as item)" to go through and open each file but I've tried several different approaches and I just can't get it to work. I've been able to make it list the directory...
13
2199
by: I. Dancay | last post by:
Can someone help me work out this project? I need someone who is a C++ expert to help me work this one out. Here it is below. implement an abstract data > type (ADT) Student as a C++ class. The project > involves writing a program > that searches for duplicates in two files with lists > of student records. The > input files must be given sorted by student name. >
10
3678
by: ibic | last post by:
Just curious: is it possible to recursively list all the directorys/files inside a given directory using standard c i/o library routines only, which can be re-compiled and run on any os supportes c compiler? Or this is too os dependent, system-specific functions must be called? I think about this when i tried to do this under windows, i found in order to achieve this, some windows-specific api such as FindFirstFile, FindNextFile must be...
19
4261
by: Ross A. Finlayson | last post by:
Hi, I hope you can help me understand the varargs facility. Say I am programming in ISO C including stdarg.h and I declare a function as so: void log_printf(const char* logfilename, const char* formatter, ...); Then, I want to call it as so:
3
2712
by: Arpi Jakab | last post by:
I have a main project that depends on projects A and B. The main project's additional include directories list is: ...\ProjectA\Dist\Include ...\ProjectB\Dist\Include Each of the include directories contain a file named "cppfile1.h". In my main project I #include "cppfile1.h". I rely on the order of paths in additional include directories list to get file cppfile1.h from ProjectA and
62
4145
by: Juuso Hukkanen | last post by:
I am looking for a wish list of things which should be removed from the C (C99) - due to feature's bad security track record <OT>or Multithreading unsafety. I need this list for a project intending to build another (easiest & most powerful) programming language, which has a two page definition document stating: "... includes C programming language (C99), except its famous "avoid-using-this-functions". </OT> If you would not want to...
2
3270
by: Juuso Hukkanen | last post by:
I need a list of multithreading unsafe C (C99) functions/features. comp.programming.threads provided an initial list of C:ish functions, with following ANSI C functions: asctime, gmtime, localtime, ctime, tmpnam, strtok http://www.lambdacs.com/cpt/FAQ.html#Q150 However, extra Googling hinted rand() and srand(), also being unsuitable for multi-threading - opinions? And what is the status of
4
1623
by: dnfertitta | last post by:
This is my task and I'd like some direction please: 1. Print company that houses user PDF files 2. User logs in and is brought to his own area 3. Dynamic customer inventory page is displayed based on PDF files in a home directory (It would be nice if the MetaTag in a PDF file could be used here)
9
1673
by: Ramashish Baranwal | last post by:
Hi, I want to get a module's contents (classes, functions and variables) in the order in which they are declared. Using dir(module) therefore doesn't work for me as it returns a list in alphabetical order. As an example- # mymodule.py class B: pass class A: pass
0
9643
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
9480
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
10083
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
9946
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
7494
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
6737
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
5379
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...
1
4044
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2877
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.