PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 25, 2022

[FIXED] How to tell if Python module is a namespace module

 November 25, 2022     module, namespaces, python, python-3.x     No comments   

Issue

In Python 3, modules can be namespace modules without an __init__.py (as per PEP 420) or as a regular module (i.e. '[modules] packages as they are implemented in Python 3.2 and earlier' - PEP 420) that have an __init__.py or are a single .py file.

How can you tell the difference between a namespace module and an 'ordinary' module?

(I am using Python 3.5.3)

e.g. Namespace module named mod prints out as:

(Pdb) mod
<module 'mymodule' (namespace)>

and ordinary modules print out as:

(Pdb) mod
<module 'mymodule' from '/path/to/mymodule/__init__.py'>

Solution

Namespace packages have a __path__, and either __file__ set to None or no __file__ attribute. (__file__ is set to None on Python 3.7 and later; previously, it was unset.)

if hasattr(mod, '__path__') and getattr(mod, '__file__', None) is None:
    print("It's a namespace package.")

In contrast, modules that aren't packages don't have a __path__, and packages that aren't namespace packages have __file__ set to the location of their __init__.py.



Answered By - user2357112
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing