Skip to content

Instantly share code, notes, and snippets.

@alvesjnr
Created July 6, 2012 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alvesjnr/3060295 to your computer and use it in GitHub Desktop.
Save alvesjnr/3060295 to your computer and use it in GitHub Desktop.

How to NOT write python codes

I found a piece of art in a code today. So I'm sharing it to you.

The guy was trying to check if a variable 'member' is a class from the module 'mod'

He figured that str(member) would return it's class representation, something like that:

>>> str(member)
<class 'polygon.rectangle.square.SimpleSquare'>

He also figured that the object 'mod' had a 'name' attribute:

>>> mod.__file__
'polygon.rectangle.square'

So, to check if the object 'member' is a class from the module 'mod' he did:

>>> if str(member).find(mod.__name__) > 0:
... 

The correct way to do this:

If you want to check if a class is from a givem module, you can use the 'inspect' package:

>>> import inspect
>>> inspect.getmodule(member) is mod
True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment