473,795 Members | 2,882 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is there a better way of accessing functions in a module?

Ant
I have the following code which works fine for running some tests
defined within a module:

def a_test():
print "Test A"

def b_test():
print "Test B"

if __name__ == "__main__":
tests = ["%s()" % x for x in dir() if x.endswith("tes t")]

for test in tests:
eval(test)

But this feels like a hack... Is there a cleaner way for accessing the
functions of the current module similar to the __dict__ attribute of
classes? i.e. a way to access the local symbol table?

Jun 13 '06 #1
6 1287
Ant

Ant wrote:
....
But this feels like a hack... Is there a cleaner way for accessing the
functions of the current module similar to the __dict__ attribute of
classes? i.e. a way to access the local symbol table?


Sorry - posted too soon. Found the globals() built-in...

Jun 13 '06 #2
Yes, you can go that route. But since it appears that what you are
doing is unit testing related, and you are interested in aranging for
all of your unit test cases to be run automatically, I'd suggest using
the unittest module.

Jun 13 '06 #3
Ant wrote:
Ant wrote:
...
But this feels like a hack... Is there a cleaner way for accessing the
functions of the current module similar to the __dict__ attribute of
classes? i.e. a way to access the local symbol table?


Sorry - posted too soon. Found the globals() built-in...


You can also
import __main__
tests = [x for x in dir(__main__) if x.endswith("tes t")]

for test in tests:
getattr(__main_ _, test)()

but I second the suggestion of looking in to unittest or one of the
other test frameworks.

Kent
Jun 13 '06 #4
"Ant" <an****@gmail.c om> writes:
def a_test():
print "Test A"

def b_test():
print "Test B"
Incidentally, the convention is to name test functions as 'test_foo'
not 'foo_test'; this will make your module more easily compatible with
existing testing tools.
if __name__ == "__main__":
tests = ["%s()" % x for x in dir() if x.endswith("tes t")]

for test in tests:
eval(test)


No need for eval. (You already found globals(), so I'll use that.)

if __name__ == "__main__":
test_funcs = [x for name, x in globals()
if name.startswith ("test") and hasattr(x, "__call__")
]

for test in test_funcs:
test()

I'll concur with other posters on this thread and encourage you to
consider using the standard 'unittest' module, and recommend 'nose'
for test discovery and execution:

<URL:http://somethingabouto range.com/mrl/projects/nose/>

--
\ "Unix is an operating system, OS/2 is half an operating system, |
`\ Windows is a shell, and DOS is a boot partition virus." -- |
_o__) Peter H. Coffin |
Ben Finney

Jun 13 '06 #5
Ben Finney wrote:
(snip)
if __name__ == "__main__":
test_funcs = [x for name, x in globals()
if name.startswith ("test") and hasattr(x, "__call__")
]


Any reason not to use callable(x) here ? (instead of hasattr(x, "__call__") )

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jun 14 '06 #6
bruno at modulix <on***@xiludom. gro> writes:
Ben Finney wrote:
(snip)
if __name__ == "__main__":
test_funcs = [x for name, x in globals()
if name.startswith ("test") and hasattr(x, "__call__")
]


Any reason not to use callable(x) here ? (instead of hasattr(x, "__call__") )


Other than my ignorance until now of 'callable', no :-)

--
\ "About four years ago, I was -- no, it was yesterday." -- |
`\ Steven Wright |
_o__) |
Ben Finney

Jun 14 '06 #7

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

Similar topics

59
3949
by: seberino | last post by:
I've heard 2 people complain that word 'global' is confusing. Perhaps 'modulescope' or 'module' would be better? Am I the first peope to have thought of this and suggested it? Is this a candidate for Python 3000 yet? Chris
2
3792
by: Bryan Olson | last post by:
The current Python standard library provides two cryptographic hash functions: MD5 and SHA-1 . The authors of MD5 originally stated: It is conjectured that it is computationally infeasible to produce two messages having the same message digest. That conjecture is false, as demonstrated by Wang, Feng, Lai and Yu in 2004 . Just recently, Wang, Yu, and Lin showed a short- cut solution for finding collisions in SHA-1 . Their result
6
8608
by: Mike | last post by:
Hi, This does sound like a bit of a weird thing to ask so I will state my question and then further down explain why I am trying to do it. So if you have the answer then reply! Or if you understand what I am trying to do and can suggest a better solution then reply also! Question -------- I want to run a VBA code module from either VB/VB.NET/C#. How can I
39
2391
by: bazad | last post by:
Hi, I am not using C all the time. I have a general understanding of C and nothing else. The recent reply to use strlcpy and strlcat showed me that I am not aware of the best and safe techniques. Is there any place where I could learn more about safer and better C (on FreeBSD)? Thank you
6
3682
by: Bob Alston | last post by:
I am looking for Access reporting add-in that would be easy to use by end users. My key focus is on selection criteria. I am very happy with the Access report writer capabilities. As far as development of reports, it is certainly fine in my book. But for end-users, with little experience or training, it would be nice to have an easy way to handle various selection criteria, perhaps with relatively stock reports. I see easy to use by...
1
3948
by: Donald Grove | last post by:
I am suddenly getting this message. It happens during code executed from a form module that calls a function stored in a standard module. I am working on a standalone pc with no network connection to anything. After this message, access closes. Then when I go back, all the module have been deleted from the form.\ MS error reporting sends me to a web page that says there isn't a fix for the problem and that I should get Access 2003 (I...
13
5317
by: Kirk | last post by:
I have been reading Scott Allen's article on Master Pages (http:// odetocode.com/Articles/450.aspx) but I am having problems understanding a concept. Specifically, I have created a property (called "CurFlag") on my master page that can be accessed from content pages, but not from separate code modules. I tried doing something like this in my VB code module: Dim myMaster As MasterPage = CType(ProjectMgmt.Master, MasterPage)
12
1820
by: reubendb | last post by:
Hello, I am new to Python. I have the following question / problem. I have a visualization software with command-line interface (CLI), which essentially is a Python (v. 2.5) interpreter with functions added to the global namespace. I would like to keep my own functions in a separate module and then import that module to the main script (that will be executed using the CLI interpreter). The problem is, I cannot access the functions in the...
3
2278
by: cjt22 | last post by:
Hi I am new to Python (I have come from a large background of Java) and wondered if someone could explain to me how I can access variables stored in my main module to other functions within other modules called from this module for example file: main.py
0
9673
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
9522
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
10165
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,...
1
7543
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
6783
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
5437
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...
0
5565
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
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
2
3728
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.