Beginner question: Python types

Paul McNett p at ulmcnett.com
Wed Jun 1 01:07:17 EDT 2005


Uppal, Deepali wrote:
> Hello,
Hello, and welcome to the world of Python. Don't take anything we say 
too personally, it is meant to help.

> I am facing a bit of a problem due to python implicitly 
> attaching a type to an object. 

Ooh. In general, don't say 'implicit'. For the most part, Python only 
does things explicitly. See the Zen of Python by opening a Python 
interpreter and typing "import this".


> I will briefly tell you the problem that
> I am facing. I am trying to print the docstring of a test case in 
> my pyUnit base test class. I accept the name of the test class as
> a command line option. So instead of printing the docstring of
> the test case, it prints the docString of a string object.

Which is expected, because all command line options are strings. I 
assume you are getting the command line option using the idiom:

import sys
options = sys.argv[1:]

> I would like to give an example here
> import test_script                                                          
> 
> gettatr( test_script.test_class.test_case, ‘__doc__’)

I think you meant:

print getattr(test_script.test_class.test_case, '__doc__')


> With this simple code, I am able to print the docstring
> of the test case.

Yep, Python is simple and expressive.


> However, since I accept the test case information as a command line
> option. So instead of printing the docstring of the test case it
> prints the docstring of a string object.

Right, because all command line options are strings, since that is all 
the shell can really hand off to Python.


> Is there someway, I can tell the script to change the type of
> the object from string to an instancetype of a test case?

In your first example, you import the test_script, and then do a 
getattr() on the test_class inside test_script.py. If you are trying to 
mimic that, and sending one or more test_script's, your code would look 
something like:

import sys

for test_module in sys.argv[1:]
	try:
		_module = __import__(test_module)
		_class = _module.test_class
		_case = _class.test_case
		print _case.__doc__
	except ImportError:
		print "Couldn't import module '%s'. Skipping..." % test_module	


> I am quite a newbie in python so I would appreciate any help on this.

The above should get you started, even though it won't satisfy your 
exact needs.

-- 
Paul McNett
http://paulmcnett.com




More information about the Python-list mailing list