5

I am writing a custom django model field which has serialize and unserialize operations, on unserialize, I am using the import_by_path to get the class and initialise an instance.

On the opposite, I need to serialize an instance to the database, in my case all I need to get the dot notation of the module.

What I am asking is, how I can, eg I have the datetime module

from datetime import datetime 

how to output datetime in dot notation to string "datetime.datetime" ?

1

2 Answers 2

10

Not entirely clear on what you're asking, but dot notation is equivalent to your above example in Python, for instance:

import datetime datetime.datetime 

is the same as

from datetime import datetime datetime 

I hope that makes sense, let me know if you have any more questions.

Here's a better example:

>>> import datetime >>> datetime <module 'datetime' from '/path/to/python'> >>> from datetime import datetime >>> datetime <type 'datetime.datetime'> 

Edit: After seeing the clarification, this should be done with the python inspect module. Specifically, if you're trying to get the module that defines a particular class:

import inspect import datetime inspect.getmodule(datetime).__name__ 

or

def dot_notation(your_module): return your_module.__module__ + "." + your_module.__class__.__name__ 

in a more general way, you can get the module

Sign up to request clarification or add additional context in comments.

7 Comments

Hi I have added the string quotes around the output, hope this makes more clear what I want to achieve
Hi I am not asking how to import modules, I am trying to get the dot notation representation of a module.
@JamesLin OOooh, I see. Updating now.
>>> from datetime import datetime >>> datetime.__module__+'.'+datetime.__class__.__name__ 'datetime.type' doesn't give me 'datetime.datetime'
@JamesLin That's why I specific called in the input your_module, use the inspect module if it's a type or an object as in the first example.
|
0
import inspect from datetime import datetime inspect.getmro(datetime)[0] 

That should return 'datetime.dateime'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.