need an alternative to getattr()

  • Thread starter pranav.choudhary
  • Start date
P

pranav.choudhary

Hi,

AIM: I have a config file that contains configuration under headings
like this:

heading1:
<configuration 1>
<configuration 2>
heading2:
<configuration 1>
<configuration 2>
....
....

i parse this file to get heading1, heading2, etc and then i want to
call heading1.process(), heading2.process(), etc.
What i am trying to do is: (this is not the exact code, it just
represents what i am trying to do)

import heading1
import heading2
While True:
heading = get_next_heading(file_ptr) # This func will return
"heading1", then "heading2"(on next call)
if heading = "":
break
getattr(heading, "process")(file_ptr) # The problem, as you would
have noticed, is that the first
# argument to getattr is a string!!

Is there an alternatice to getattr() that will solve my problem, or is
there another way to do it.

-pranav
 
U

Uffe Wassmann

I think you would benefit from looking at the ConfigParser module.
I haven't tried it yet, but it looks like a nice interface for writing
and reading configuration files.

-Uffe.
 
A

Ant

getattr(heading, "process")(file_ptr) ....
Is there an alternatice to getattr() that will solve my problem, or is
there another way to do it.

How about:

eval("%s.process(%s)" % (heading, file_ptr))
 
J

Jon Ribbens

import heading1
import heading2
While True:
heading = get_next_heading(file_ptr) # This func will return
"heading1", then "heading2"(on next call)
if heading = "":
break
getattr(heading, "process")(file_ptr) # The problem, as you would
have noticed, is that the first
# argument to getattr is a string!!

Is there an alternatice to getattr() that will solve my problem, or is
there another way to do it.

globals()
.process(file_ptr)

or

sys.modules
.process(file_ptr)

but note that, unless you are checking 'heading' against a 'known
good configuration keywords' list beforehand, you are trusting the
author of the configuration file.​
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top