4

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" ?

James Lin
  • 20,109
  • 28
  • 106
  • 192
  • possible duplicate of [Get fully qualified class name of an object in python](http://stackoverflow.com/questions/2020014/get-fully-qualified-class-name-of-an-object-in-python) – BrenBarn Apr 02 '14 at 02:20

2 Answers2

8

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

Slater Victoroff
  • 19,762
  • 18
  • 78
  • 135
1
import inspect

from datetime import datetime


inspect.getmro(datetime)[0]

That should return 'datetime.dateime'

man2xxl
  • 1,103
  • 11
  • 23