Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a dot notation of a python module?

Tags:

python

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

like image 998
James Lin Avatar asked Jan 11 '23 21:01

James Lin


1 Answers

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

like image 122
Slater Victoroff Avatar answered Jan 19 '23 00:01

Slater Victoroff