472,967 Members | 1,853 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,967 software developers and data experts.

Module listing in order.

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
class D: pass

# test.py
import mymodule
# This returns['A', 'B', 'D', '__builtins__', '__doc__', '__file__',
'__name__']
contents = dir(mymodule)

I want a way to get the contents in the order of their declaration,
i.e. [B, A, D]. Does anyone know a way to get it?

Thanks,
Ram

May 23 '07 #1
9 1635
En Wed, 23 May 2007 04:32:42 -0300, Ramashish Baranwal
<ra*************@gmail.comescribió:
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
Once the module is created, you can't: its namespace is a dictionary, with
no key ordering.
So you have to play with the module creation: get some kind of dictionary
that remembers insertion order, and use it as the globals argument to
__import__. (Some builtin operations require a true dictionary or use it
in a non-polimorphic way, so this may or may not work - you'll have to try
and please follow up with your findings)

--
Gabriel Genellina

May 23 '07 #2
Ramashish Baranwal wrote:
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
class D: pass

# test.py
import mymodule
# This returns['A', 'B', 'D', '__builtins__', '__doc__', '__file__',
'__name__']
contents = dir(mymodule)

I want a way to get the contents in the order of their declaration,
i.e. [B, A, D]. Does anyone know a way to get it?
Whatfor do you actually need this? Is it a general interest - then things
get difficult. But for certain usecases, metaclasses might come to the
rescue. But that depends on what you want to do.

Diez
May 23 '07 #3
Ramashish Baranwal wrote:
I want a way to get the contents in the order of their declaration,
i.e. [B, A, D]. Does anyone know a way to get it?
My suggestion would be to actually parse the text of the module. "Brute
force" is what it's called ;). But doing so with, say, pyparsing
shouldn't be *very* difficult.

Just out of curiosity: Why do you need the order?

W
May 23 '07 #4
I want a way to get the contents in the order of their declaration,
i.e. [B, A, D]. Does anyone know a way to get it?

My suggestion would be to actually parse the text of the module. "Brute
force" is what it's called ;). But doing so with, say, pyparsing
shouldn't be *very* difficult.

Just out of curiosity: Why do you need the order?
Thank you for your replies, and sorry for my late response.

Gabriel, unfortunately I am not a python expert so don't know how to
play with module creation. I tried to look into __import__ function,
but can't see a way to get what I want.

Wildemar, your approach seems workable. I am going to have a look at
it.

Well, my requirement doesn't turn out to be an actual requirement
now.:) I am using a web framework Django, that lets you define classes
for database tables. The classes so defined can refer to other classes
representing db tables. It also allows you to export those table data
in a db-neutral format e.g. xml via the python classes so defined.
Exporting does not require an order, but I thought that importing the
data back may require data of classes which are referred by other
classes to be present. I just verified that its not so. So I don't
need to do it immediately.

Nevertheless, it would be interesting to see how it can be done.:)

-Ram

May 25 '07 #5
Ramashish Baranwal wrote:
I want a way to get the contents in the order of their declaration,
i.e. [B, A, D]. Does anyone know a way to get it?

My suggestion would be to actually parse the text of the module. "Brute
force" is what it's called ;). But doing so with, say, pyparsing
shouldn't be *very* difficult.
Nevertheless, it would be interesting to see how it can be done.:)
>>import pyclbr
classes = pyclbr.readmodule("mymodule")
sorted(classes, key=lambda name: classes[name].lineno)
['B', 'A', 'D']

Peter
May 25 '07 #6
Peter Otten wrote:
Ramashish Baranwal wrote:

>>>I want a way to get the contents in the order of their declaration,
i.e. [B, A, D]. Does anyone know a way to get it?

My suggestion would be to actually parse the text of the module. "Brute
force" is what it's called ;). But doing so with, say, pyparsing
shouldn't be *very* difficult.

>Nevertheless, it would be interesting to see how it can be done.:)

>>>import pyclbr
classes = pyclbr.readmodule("mymodule")
sorted(classes, key=lambda name: classes[name].lineno)
['B', 'A', 'D']

Good God! Is there *anything* that python does not already do? I hardly
feel the need to write programs anymore ...
Its really 80% like of the questions that are asked here get answered
along the lines of:

import some_fancy_module

solution = some_fancy_module.exactly_the_right_function_to_so lve(problem)

Kinda scary ... :)
W
May 26 '07 #7
Wildemar Wildenburger wrote:
Peter Otten wrote:
>Ramashish Baranwal wrote:

>>>>I want a way to get the contents in the order of their declaration,
i.e. [B, A, D]. Does anyone know a way to get it?
>
My suggestion would be to actually parse the text of the module. "Brute
force" is what it's called ;). But doing so with, say, pyparsing
shouldn't be *very* difficult.
>>Nevertheless, it would be interesting to see how it can be done.:)
>>>>import pyclbr
classes = pyclbr.readmodule("mymodule")
sorted(classes, key=lambda name: classes[name].lineno)
>
['B', 'A', 'D']


Good God! Is there *anything* that python does not already do? I hardly
feel the need to write programs anymore ...
+1 QOTW
Its really 80% like of the questions that are asked here get answered
along the lines of:

import some_fancy_module

solution = some_fancy_module.exactly_the_right_function_to_so lve(problem)

Kinda scary ... :)
And you haven't seen the time machine working yet ...

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com squidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------

May 26 '07 #8
In article <ma***************************************@python. org>,
Wildemar Wildenburger <wi******@freakmail.dewrote:
May 26 '07 #9
Ramashish Baranwal <ra*************@gmail.comwrote:
I want a way to get the contents in the order of their declaration,
i.e. [B, A, D]. Does anyone know a way to get it?
My suggestion would be to actually parse the text of the module. "Brute
force" is what it's called ;). But doing so with, say, pyparsing
shouldn't be *very* difficult.

Just out of curiosity: Why do you need the order?
Thank you for your replies, and sorry for my late response.

Gabriel, unfortunately I am not a python expert so don't know how to
play with module creation. I tried to look into __import__ function,
but can't see a way to get what I want.

Wildemar, your approach seems workable. I am going to have a look at
it.

Well, my requirement doesn't turn out to be an actual requirement
now.:) I am using a web framework Django, that lets you define classes
for database tables. The classes so defined can refer to other classes
representing db tables. It also allows you to export those table data
in a db-neutral format e.g. xml via the python classes so defined.
Exporting does not require an order, but I thought that importing the
data back may require data of classes which are referred by other
classes to be present. I just verified that its not so. So I don't
need to do it immediately.
Actually I had a requirement to do exactly this. I was using python
as a definition language, making classes to define other things. It
worked very nicely but I needed to get the classes in definition
order.

Here is how I did it with metaclasses

class _Definition_Metaclass(type):
"""
A metaclass to add a _class_sequence attribute to each definition so we know
which order they were defined in.
"""
_class_sequence = 0
def __init__(cls, name, bases, dict):
_class_sequence = _Definition_Metaclass._class_sequence
_Definition_Metaclass._class_sequence += 1
cls._class_sequence = _class_sequence

class Definition(object):
__metaclass__ = _Definition_Metaclass

class A(Definition): pass

class B(A): pass

class C(A): pass

class D(Definition): pass

class E(C): pass

objects = []
for obj in locals().values():
try:
if issubclass(obj, Definition):
objects.append(obj)
except TypeError:
pass

objects_sorted = sorted(objects, key=lambda x: x._class_sequence)

print objects

# Gives something like
# [<class '__main__.A'>, <class '__main__.Definition'>, <class
# '__main__.C'>, <class '__main__.B'>, <class '__main__.E'>, <class
# '__main__.D'>]

print objects_sorted

# Gives
# [<class '__main__.Definition'>, <class '__main__.A'>, <class
# '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>, <class
# '__main__.E'>]
--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
May 29 '07 #10

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

Similar topics

15
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...
0
by: mg | last post by:
Hi everybody... I am using Python API in order to create bindings. So, in the init function of my module, I create constants : PyMODINIT_FUNC initMyModule( void ) { PyObject* module =...
4
by: Andrew E | last post by:
Hi all I've written a python program that adds orders into our order routing simulation system. It works well, and has a syntax along these lines: ./neworder --instrument NOKIA --size 23...
2
by: TNGgroup | last post by:
Hi, a Simple Question, I have some code at my form, the code in the form is calling a certain module and execute some code, a certain variable is set to strTemp. but when de module is done. I...
5
by: Bruce Lawrence | last post by:
I'm running Access 97 and my modules are looping if someone puts an invalid value in. The setup: 3 macros - get_clock_num, verify_clocknum, append_to_history 3 functions. each in their own...
3
by: Alpha | last post by:
This is a Window based application. How do I get my combox listing to display in sorted order by DataMember? I inserted a blank row to the dataset table which is the datasrouce for the comboBox...
4
by: John please don't spam me! | last post by:
Hi Guys, I writing a project with just one module in it (the reason for this is to debug code before it becomes a service) and am getting an error which I do not understand: No accessible...
1
by: sh | last post by:
I have a web service which works fine. I want to offload some functions into a separate module, but as soon as I add an empty module to my project and test it, my web methods don't show up anymore....
0
by: Lie | last post by:
Yesterday I installed compiz-icon in my Ubuntu. Today, when I go to the python interpreter, I happen to do this: ### START OF PYTHON SESSION ### Python 2.5.2 (r252:60911, Apr 21 2008, 11:17:30)...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

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.