Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #12776 > unrolled thread

Best way to print a module?

Started byMartin De Kauwe <mdekauwe@gmail.com>
First post2011-09-05 08:06 -0700
Last post2011-09-06 09:46 +1000
Articles 6 — 4 participants

Back to article view | Back to comp.lang.python


Contents

  Best way to print a module? Martin De Kauwe <mdekauwe@gmail.com> - 2011-09-05 08:06 -0700
    Re: Best way to print a module? rantingrick <rantingrick@gmail.com> - 2011-09-05 09:30 -0700
    Re: Best way to print a module? Tim Roberts <timr@probo.com> - 2011-09-05 13:07 -0700
      Re: Best way to print a module? Martin De Kauwe <mdekauwe@gmail.com> - 2011-09-05 16:02 -0700
        Re: Best way to print a module? Martin De Kauwe <mdekauwe@gmail.com> - 2011-09-05 16:20 -0700
      Re: Best way to print a module? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-09-06 09:46 +1000

#12776 — Best way to print a module?

FromMartin De Kauwe <mdekauwe@gmail.com>
Date2011-09-05 08:06 -0700
SubjectBest way to print a module?
Message-ID<00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com>
Hi,

If I wanted to print an entire module, skipping the attributes
starting with "__" is there an *optimal* way? Currently I am doing
something like this. Note I am just using sys here to make the point

import sys

data = []
for attr in sys.__dict__.keys():
    if not attr.startswith('__') and not attr.endswith('__'):
        attr_val = getattr(sys, attr)
        data.append((attr, attr_val))
data.sort()
for i in data:
    print "%s = %s" % (i[0], i[1])

Clearly this would be quicker if I didn't store it and sort the
output, i.e.

for attr in sys.__dict__.keys():
    if not attr.startswith('__') and not attr.endswith('__'):
        attr_val = getattr(sys, attr)
        print "%s = %s" % (attr, attr_val)

Anyway if there is a better way it would be useful to hear it...

Many thanks,

Martin

[toc] | [next] | [standalone]


#12784

Fromrantingrick <rantingrick@gmail.com>
Date2011-09-05 09:30 -0700
Message-ID<0460d27a-ce73-40f5-a31a-6772eacb7784@l7g2000vbz.googlegroups.com>
In reply to#12776
On Sep 5, 10:06 am, Martin De Kauwe <mdeka...@gmail.com> wrote:
> Hi,
>
> If I wanted to print an entire module, skipping the attributes
> starting with "__" is there an *optimal* way? Currently I am doing
> something like this. Note I am just using sys here to make the point
>
> import sys
>
> data = []
> for attr in sys.__dict__.keys():
>     if not attr.startswith('__') and not attr.endswith('__'):
>         attr_val = getattr(sys, attr)
>         data.append((attr, attr_val))
> data.sort()
> for i in data:
>     print "%s = %s" % (i[0], i[1])
>
> Clearly this would be quicker if I didn't store it and sort the
> output, i.e.
>
> for attr in sys.__dict__.keys():
>     if not attr.startswith('__') and not attr.endswith('__'):
>         attr_val = getattr(sys, attr)
>         print "%s = %s" % (attr, attr_val)
>
> Anyway if there is a better way it would be useful to hear it...
>
> Many thanks,
>
> Martin

Martin, have you considered that your custom function is just re-
inventing the built-in dir() function? I would suggest using a list
comprehension against the dir() function with a predicate to remove
anything that startswith '_'. Here's some Ruby code to solve the
problem. I'll let you figure out the Python equivalent.

rb> ['_hello', '__goodbye__', 'whatsup'].select{|x| x[0].chr != '_'}
["whatsup"]

[toc] | [prev] | [next] | [standalone]


#12789

FromTim Roberts <timr@probo.com>
Date2011-09-05 13:07 -0700
Message-ID<traa67hlthgbqrinmvpectcvd4la9lfams@4ax.com>
In reply to#12776
Martin De Kauwe <mdekauwe@gmail.com> wrote:
>
>If I wanted to print an entire module, skipping the attributes
>starting with "__" is there an *optimal* way? 

Your question is somewhat ambiguous.  When I read "print an entire module",
I assumed you were asking for a way to print the source code, perhaps with
syntax coloring.

Surely there is no reason to have an "optimal" method of doing this -- this
is never going to be in an inner loop.  If you have a method that works,
there is little justification to optimize...
-- 
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.

[toc] | [prev] | [next] | [standalone]


#12797

FromMartin De Kauwe <mdekauwe@gmail.com>
Date2011-09-05 16:02 -0700
Message-ID<9c0733c8-875b-425a-9021-5f22bf75d1a6@m4g2000pri.googlegroups.com>
In reply to#12789
Hi,

Tim yes I had a feeling my posting might be read as ambiguous! Sorry I
was trying to quickly think of a good example. Essentially I have a
set of .ini parameter files which I read into my program using
configobj, I then replace the default module parameters if the user
file is different (in my program). When it comes to writing the data
back out I need to potentially loop over 5 module files and I need to
ignore the superfluous information. My guess is that the way I am
doing it might be a little on the slow side, hence the posting. Like
you said it might be that the way I am doing it is "fine", I just
wanted to see if there was a better way that is all.

Rantingrick I did actually try the dir() to start with, I can't
remember why I changed back. I will try your suggestion and see
(thanks)

So instead of sys as per my example my module more realistically looks
like this:

params.py

apples = 12.0
cats = 14.0
dogs = 1.3

so my fuller example then

import sys
sys.path.append("/Users/mdekauwe/Desktop/")
import params

#params.py contains
#apples = 12.0
#cats = 14.0
#dogs = 1.3

fname = "test.asc"
try:
    ofile = open(fname, 'w')
except IOError:
    raise IOError("Can't open %s file for write" % fname)

data = []
for attr in params.__dict__.keys():
    if not attr.startswith('__') and not attr.endswith('__'):
        attr_val = getattr(params, attr)
        data.append((attr, attr_val))

data.sort()
try:
    ofile.write("[params]\n")
    for i in data:
        ofile.write("%s = %s\n" % (i[0], i[1]))
except IOError:
    raise IOError("Error writing params files, params section")


etc, etc
thanks

[toc] | [prev] | [next] | [standalone]


#12800

FromMartin De Kauwe <mdekauwe@gmail.com>
Date2011-09-05 16:20 -0700
Message-ID<5de6e076-f25a-4a44-ba9b-2c99ff006565@e20g2000prn.googlegroups.com>
In reply to#12797
Trying to follow the suggestion this would be the alternate
implementation.

import sys
sys.path.append("/Users/mdekauwe/Desktop/")
import params

#params.py contains
#apples = 12.0
#cats = 14.0
#dogs = 1.3

fname = "test.asc"
try:
    ofile = open(fname, 'w')
except IOError:
    raise IOError("Can't open %s file for write" % fname)

attributes = [attr for attr in dir(params) if not
attr.startswith('__')]
attributes.sort()

try:
    ofile.write("[params]\n")
    for i in attributes:
        ofile.write("%s = %s\n" % (i, getattr(params, i)))
except IOError:
    raise IOError("Error writing params files, params section")

Is that a better version? I honestly don't know.

thanks

[toc] | [prev] | [next] | [standalone]


#12802

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2011-09-06 09:46 +1000
Message-ID<4e655f4a$0$29965$c3e8da3$5496439d@news.astraweb.com>
In reply to#12789
Tim Roberts wrote:

> Martin De Kauwe <mdekauwe@gmail.com> wrote:
>>
>>If I wanted to print an entire module, skipping the attributes
>>starting with "__" is there an *optimal* way?
> 
> Your question is somewhat ambiguous.  When I read "print an entire
> module", I assumed you were asking for a way to print the source code,
> perhaps with syntax coloring.
> 
> Surely there is no reason to have an "optimal" method of doing this --
> this is never going to be in an inner loop.

Regardless of an inner loop or not, the time required for IO (reading the
file from disk, writing it to a printer) will be much larger than the time
required to skip dunder (double-underscore) objects.

> If you have a method that works, 
> there is little justification to optimize...

Pretty much.

HOWEVER, having agreed with you in general, in this specific case it is
obvious to me from context that the OP doesn't want to print the source
code of the module, but the module's names and their values.

I'd try a couple of approaches:

- use dir() or vars() to get the module's names, then loop and print each
one;

- make a shallow copy of the module __dict__, less dunder names, and pass it
to the prettyprint module for printing.



-- 
Steven

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web