简体   繁体   中英

How to get a dot notation of a python module?

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

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

import inspect

from datetime import datetime


inspect.getmro(datetime)[0]

That should return 'datetime.dateime'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM