473,379 Members | 1,255 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 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 1657
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)...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.